55 Python Interview Questions and Answers (Concepts, Coding, Output)

55 Python interview questions and answers banner from Coursack
Data and Python Interview Questions

55 Python Interview Questions and Answers (Concepts, Coding, Output)

⏱ Updated November 202655 questions14 min read

Preparing for a Python interview? These 55 questions mix concepts, programming problems and “guess the output” puzzles, the way real interviews test Python. Expand each one to see the code, the output and why. Then build your skills with our Python for Data Science Training.

Python Core Concepts

1. What are the key features of Python, and why is it popular for data work?

Python is interpreted, dynamically typed, readable, and has a huge ecosystem (NumPy, pandas, scikit-learn, Django, FastAPI). It supports several paradigms: procedural, object-oriented and functional. Its readability and libraries make it quick to prototype and productive for data analysis, automation and web back ends.

2. What is the difference between a list, tuple, set and dictionary?

A list is an ordered, mutable sequence. A tuple is ordered and immutable, so it can be a dictionary key if its items are hashable. A set is an unordered collection of unique hashable items with fast membership tests. A dictionary maps keys to values and keeps insertion order in modern Python.

[1, 2, 2]        list   -> allows duplicates, mutable
(1, 2, 2)        tuple  -> immutable
{1, 2}           set    -> unique, unordered
{"a": 1}         dict   -> key to value
3. What is the difference between == and is?

== compares values using __eq__, while is compares object identity (the same object in memory). Use is for None checks (x is None) and == for value comparison.

Want to answer these with confidence? Learn it live with an instructor.View data courses
4. Explain mutable and immutable types with examples.

Immutable objects cannot change after creation: int, float, str, tuple, frozenset, bytes. Mutable objects can change in place: list, dict, set and most custom classes. This matters for default arguments, dictionary keys and passing objects to functions.

5. What is the difference between shallow copy and deep copy?

A shallow copy creates a new container but shares the nested objects; a deep copy recursively copies everything. Use copy.deepcopy when nested mutable objects must be independent.

import copy
a = [[1, 2], [3]]
s = copy.copy(a)
d = copy.deepcopy(a)
a[0].append(99)
print(s)  # [[1, 2, 99], [3]]  (shared inner list)
print(d)  # [[1, 2], [3]]      (independent)
6. How does Python manage memory?

Python uses a private heap, reference counting for immediate cleanup, and a cyclic garbage collector to free reference cycles. Small objects use a pool allocator for speed. You rarely manage memory manually, but you should avoid keeping unnecessary references, and use generators for large data.

7. What is the GIL, and how does it affect multithreading?

The Global Interpreter Lock allows only one thread to execute Python bytecode at a time in standard CPython, so CPU-bound threads do not run in parallel. Use multiprocessing for CPU-bound work, and threads or asyncio for I/O-bound work. Recent Python versions also offer an optional free-threaded build, so check what your version supports.

8. What are *args and **kwargs?

*args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. They let functions accept flexible inputs and forward them to other functions.

def show(*args, **kwargs):
    print(args, kwargs)
show(1, 2, name="Asha")   # (1, 2) {'name': 'Asha'}
9. What are list comprehensions, and when should you avoid them?

They create lists concisely from iterables with optional filters, and are usually faster and clearer than loops. Avoid them when the logic is long or nested, or when you only need to iterate once, where a generator expression saves memory.

squares = [x*x for x in range(6) if x % 2 == 0]   # [0, 4, 16]
total = sum(x*x for x in range(10**6))             # generator, no list
10. Explain Python’s LEGB rule.

Name lookup searches Local, Enclosing function, Global, then Built-in scopes. Use the global or nonlocal keywords to rebind names from outer scopes, but prefer passing values explicitly.

Functions, OOP and Advanced Concepts

11. What is a decorator, and how do you write one?

A decorator is a function that wraps another function to add behaviour without changing its code, such as logging, caching or authentication. Use functools.wraps to preserve the original function’s metadata.

import functools, time
def timed(fn):
    @functools.wraps(fn)
    def wrapper(*a, **k):
        t = time.perf_counter()
        out = fn(*a, **k)
        print(fn.__name__, time.perf_counter() - t)
        return out
    return wrapper

@timed
def work(): return sum(range(10**6))
12. What is the difference between an iterator, an iterable and a generator?

An iterable can produce an iterator (it has __iter__), an iterator has __next__ and remembers its position, and a generator is a function with yield that creates an iterator lazily. Generators handle large or infinite sequences with minimal memory.

def count_up(n):
    for i in range(n):
        yield i
g = count_up(3)
print(next(g), next(g))   # 0 1
13. What are __init__, __str__ and __repr__ used for?

__init__ initialises a new object, __str__ returns a readable string for users (print), and __repr__ returns an unambiguous developer representation, ideally one that could recreate the object. Define __repr__ at least.

14. Explain inheritance and the method resolution order (MRO).

A subclass inherits from parents. With multiple inheritance, Python uses C3 linearisation to decide the lookup order, visible via ClassName.__mro__. super() follows the MRO, so cooperative multiple inheritance works if every class calls super().

class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print([k.__name__ for k in D.__mro__])  # ['D','B','C','A','object']
15. What is the difference between @staticmethod, @classmethod and an instance method?

An instance method receives self and works on one object. A classmethod receives cls and works with the class, often as an alternative constructor. A staticmethod receives neither and is just a function grouped inside the class namespace.

16. What are dataclasses, and why use them?

The @dataclass decorator generates __init__, __repr__ and __eq__ from type-annotated fields, reducing boilerplate for classes that mainly hold data. Options like frozen=True make instances immutable.

from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
    x: int
    y: int
print(Point(1, 2))   # Point(x=1, y=2)
17. How does exception handling work, and what are try, except, else and finally?

try holds code that may fail, except handles specific errors, else runs if no exception occurred, and finally always runs for cleanup. Catch specific exceptions, avoid bare except, and use raise from to keep the cause.

try:
    n = int(input())
except ValueError:
    print("not a number")
else:
    print("ok", n)
finally:
    print("done")
18. What is a context manager, and why use the with statement?

It guarantees setup and cleanup around a block, even on errors, such as closing files or releasing locks. Implement __enter__ and __exit__, or use contextlib.contextmanager.

with open("data.txt") as f:
    text = f.read()   # file closed automatically
19. When do you use threading, multiprocessing and asyncio?

Threading suits I/O-bound tasks with blocking libraries, multiprocessing suits CPU-bound tasks since each process has its own interpreter, and asyncio suits many concurrent I/O operations with non-blocking code. Choose based on whether the bottleneck is CPU or waiting.

20. What are lambda, map, filter and reduce? Are they preferred over comprehensions?

A lambda is a small anonymous function. map applies a function to items, filter keeps items that pass a test, and reduce (from functools) folds items to one value. Comprehensions are usually more readable in Python, so use map and filter mainly with existing named functions.

Guess the Output

21. Guess the output: floating point comparison

Floating point numbers are stored in binary, so 0.1 and 0.2 cannot be represented exactly. Use math.isclose or the decimal module for comparisons.

print(0.1 + 0.2 == 0.3)
print(0.1 + 0.2)
# Output:
# False
# 0.30000000000000004
22. Guess the output: mutable default argument

The default list is created once when the function is defined and shared across calls. Use None as the default and create a new list inside.

def add(x, items=[]):
    items.append(x)
    return items
print(add(1))
print(add(2))
# Output:
# [1]
# [1, 2]
23. Guess the output: list aliasing

b = a does not copy the list; both names refer to the same object.

a = [1, 2, 3]
b = a
b.append(4)
print(a)
# Output: [1, 2, 3, 4]
24. Guess the output: integer division and modulo with negatives

// floors toward negative infinity, and the result of % takes the sign of the divisor.

print(7 // 2, -7 // 2, 7 % -3)
print(type(1 / 2))
# Output:
# 3 -4 -2
# <class 'float'>
25. Guess the output: slicing

Slices never raise IndexError for out-of-range bounds; they return what exists.

x = [1, 2, 3]
print(x[::-1], x[-2:], x[5:])
# Output: [3, 2, 1] [2, 3] []

Build your skills in Data and Python

Join the next live batch with an instructor. Small batches, real projects and a free demo class before you decide.

26. Guess the output: truthiness

Empty containers and empty strings are falsy; non-empty ones, even containing zero or a space, are truthy.

print(bool([]), bool([0]), bool(""), bool(" "))
# Output: False True False True
27. Guess the output: late binding in closures

The lambda looks up i when called, after the loop has finished, so all lambdas see the final value 2. Bind it with a default argument: lambda i=i: i.

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
# Output: [2, 2, 2]
28. Guess the output: dictionary keys 1, 1.0 and True

1, 1.0 and True are equal and have the same hash, so they map to the same key. The key keeps its first spelling, and the value is the last one assigned.

d = {}
d[1] = "a"
d[1.0] = "b"
d[True] = "c"
print(d)
# Output: {1: 'c'}
29. Guess the output: tuple holding a list

The tuple itself is immutable, but the list inside it is mutable.

t = (1, [2, 3])
t[1].append(4)
print(t)
# Output: (1, [2, 3, 4])
# t[0] = 9  would raise TypeError
30. Guess the output: generator exhaustion

A generator can be consumed only once; the second list() finds it empty.

g = (x * x for x in range(3))
print(list(g))
print(list(g))
# Output:
# [0, 1, 4]
# []
31. Guess the output: finally with return

The finally block runs before the function returns its value.

def f():
    try:
        return 1
    finally:
        print("done")
print(f())
# Output:
# done
# 1
32. Guess the output: UnboundLocalError

Because x is assigned inside the function, Python treats it as local for the whole function, so reading it before assignment fails.

x = 10
def f():
    print(x)
    x = 5
f()
# Output: UnboundLocalError: cannot access local variable 'x' ...
33. Guess the output: banker’s rounding

Python 3 rounds halves to the nearest even number.

print(round(2.5), round(3.5), round(-2.5))
# Output: 2 4 -2
34. Guess the output: class variable shared between instances

items is a class attribute, so every instance shares the same list.

class A:
    items = []
a, b = A(), A()
a.items.append(1)
print(b.items)
# Output: [1]

Coding Questions

35. Reverse a string and check if it is a palindrome.

Use slicing, and normalise case and non-alphanumeric characters if the problem asks for it.

def is_palindrome(s):
    t = [c.lower() for c in s if c.isalnum()]
    return t == t[::-1]
print(is_palindrome("A man, a plan, a canal: Panama"))  # True
36. Solve Two Sum: return the indices of two numbers that add up to a target.

Use a dictionary of value to index for O(n) time instead of a nested loop.

def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        if target - n in seen:
            return [seen[target - n], i]
        seen[n] = i
print(two_sum([2, 7, 11, 15], 9))   # [0, 1]
37. Find the first non-repeating character in a string.

Count with collections.Counter, then scan again in order.

from collections import Counter
def first_unique(s):
    c = Counter(s)
    return next((ch for ch in s if c[ch] == 1), None)
print(first_unique("swiss"))   # w
38. Remove duplicates from a list while preserving order.

Use dict.fromkeys (insertion ordered) or a seen set.

items = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(items)))   # [3, 1, 2]
39. Count word frequency in a text and show the top 3.

Split, normalise, and use Counter.most_common.

from collections import Counter
text = "to be or not to be"
print(Counter(text.split()).most_common(3))
# [('to', 2), ('be', 2), ('or', 1)]
40. Flatten a nested list of arbitrary depth.

Use recursion with a generator.

def flatten(xs):
    for x in xs:
        if isinstance(x, list):
            yield from flatten(x)
        else:
            yield x
print(list(flatten([1, [2, [3, 4]], 5])))   # [1, 2, 3, 4, 5]
41. Check whether two strings are anagrams.

Compare sorted characters or Counters.

from collections import Counter
def anagram(a, b):
    return Counter(a.lower()) == Counter(b.lower())
print(anagram("Listen", "Silent"))   # True
42. Write a function that returns the nth Fibonacci number efficiently.

A recursive version is exponential; use memoisation or iteration.

from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n-1) + fib(n-2)
print(fib(50))   # 12586269025

Files, Modules and Practical Python

43. How do you read a large CSV file without loading it all into memory?

Iterate line by line with the csv module, or read in chunks with pandas.read_csv(chunksize=…), processing and aggregating each chunk.

import pandas as pd
total = 0
for chunk in pd.read_csv("big.csv", chunksize=100_000):
    total += chunk["amount"].sum()
44. What is a virtual environment, and why use one?

It is an isolated Python environment with its own packages, so projects with different dependency versions do not conflict. Create it with python -m venv .venv, install with pip, and record dependencies in requirements.txt or pyproject.toml.

45. What is the difference between a module, a package and a library?

A module is a single .py file, a package is a directory of modules (with an __init__.py or as a namespace package), and a library is a collection of packages that provides functionality, like NumPy.

46. What does if __name__ == “__main__” do?

It runs code only when the file is executed directly, not when it is imported as a module. It lets a file serve as both a reusable module and a script.

47. How do you write unit tests in Python?

Use pytest (or unittest), write small tests with clear assertions, use fixtures for setup, parametrise to cover cases, and mock external services. Aim for fast, independent tests.

import pytest
def add(a, b): return a + b
@pytest.mark.parametrize("a,b,r", [(1,2,3), (0,0,0), (-1,1,0)])
def test_add(a, b, r):
    assert add(a, b) == r
48. What are type hints, and do they affect runtime?

Type hints document expected types and enable tools like mypy or IDEs to catch errors, but Python does not enforce them at runtime. They improve readability and maintainability in larger codebases.

def greet(name: str, times: int = 1) -> str:
    return (f"Hi {name} ") * times
49. How do you handle JSON and call a REST API in Python?

Use the requests or httpx library, set timeouts, check status codes and parse JSON with response.json().

import requests
r = requests.get("https://api.example.com/items", timeout=10)
r.raise_for_status()
items = r.json()
50. How would you profile and speed up slow Python code?

Measure first with cProfile or timeit, then fix the real hotspot: better algorithms and data structures (sets and dicts for lookups), avoid repeated work with caching, use vectorised NumPy or pandas operations, and move heavy loops to compiled libraries or multiprocessing.

Python for Data and Interview Scenarios

51. What is the difference between a NumPy array and a Python list?

NumPy arrays hold elements of one type in contiguous memory and support vectorised operations, which are far faster and more memory-efficient for numerical work. Lists are flexible but slower for math.

import numpy as np
a = np.array([1, 2, 3])
print(a * 2)       # [2 4 6]
print([1, 2, 3] * 2)  # [1, 2, 3, 1, 2, 3]
52. How would you clean a messy CSV with missing values and inconsistent formats?

Load it, inspect with info and describe, standardise column names and types, handle missing values by dropping, filling or flagging, fix inconsistent categories, validate with assertions, and save a cleaned copy. Keep the steps in a script so they are repeatable. See our Pandas and SQL questions for the hands-on part.

53. Explain how you would build a simple REST API in Python.

Use FastAPI or Flask: define routes, validate input with Pydantic models, connect to a database through an ORM, handle errors with proper status codes, add authentication, write tests and run behind a production server like Uvicorn or Gunicorn.

from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health():
    return {"status": "ok"}
54. What are Python’s common design patterns you have used?

Examples: factory for creating objects by type, singleton through module-level instances, strategy by passing functions as arguments, decorator for cross-cutting behaviour and observer for events. Python’s first-class functions often replace heavier patterns.

55. How do you keep up with Python changes?

Read the “What’s New” notes for each release, follow PEPs for features you use, run tests against new versions in CI, and update type hints and syntax gradually. Our programming languages guide shows where Python sits today.

Build your Python skills

Continue with our Pandas and SQL interview questions, read what changed in Python 3.8, or start the Python for Data Science Training.

Related question sets

Prepare with a mentor. Try a class before you decide.WhatsAppBook a free demo
Share this set

Leave your thought here

Your email address will not be published. Required fields are marked *

Alert: You are not allowed to copy content or view source !!