Python Interview Preparation
You've completed the entire Python tutorial — now it's time to ace your interview! This chapter covers the Top 50 Python interview questions with detailed answers, from beginner to advanced level, covering all topics interviewers actually test: data types, OOP, decorators, generators, memory management, async programming, data structures, and real coding challenges. Plus 25 MCQ practice questions to self-assess your readiness.
Interview Preparation Roadmap
Companies test Python across four stages. Know what to expect and prepare accordingly:
Basic Python — Questions 1 to 15 Basic
List: mutable (can change after creation), uses [], slightly slower, can be used as dict values but NOT as dict keys.
Tuple: immutable (cannot change), uses (), faster iteration, hashable so CAN be dict keys or set members. Use
tuples for fixed data (coordinates, RGB values, database records).
lst = [1,2,3]; lst[0] = 99 # OK
tpl = (1,2,3); tpl[0] = 99 # TypeError!
d = {(1,2): "point"} # tuple as key — OK
== compares values (calls __eq__). is compares
identity — whether two variables point to the exact same object in memory (same id()).
a = [1,2]; b = [1,2]
a == b # True — same value
a is b # False — different objects
c = a
a is c # True — same object
Use is only for singletons: None, True, False. Never use is to compare
strings or integers beyond small cached values.
*args collects extra positional arguments as a
tuple. **kwargs collects extra keyword arguments as
a dict.
def demo(*args, **kwargs):
print(args) # (1, 2, 3)
print(kwargs) # {'name': 'Alice', 'age': 25}
demo(1, 2, 3, name="Alice", age=25)
Python resolves names in this order: Local → Enclosing (closure) →
Global → Built-in. If a name isn't found in any scope, NameError is raised.
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # "local"
inner()
Default argument values are evaluated once at function definition, not on each call.
Using a mutable default (like []) means all calls share the same
object — a very common Python bug.
# ❌ Bug:
def add(item, lst=[]):
lst.append(item); return lst
add(1) # [1]
add(2) # [1, 2] ← shared!
# ✅ Fix:
def add(item, lst=None):
if lst is None: lst = []
lst.append(item); return lst
A dict is a hash map — keys are hashed to find their storage slot. This gives O(1) average-case lookup, insertion, and deletion. Only hashable objects (immutable: int, str, tuple) can be keys. Since Python 3.7+, dicts maintain insertion order.
Collision resolution: Python uses open addressing (probing). When the load factor exceeds ~2/3, the hash table is resized (doubled), which is why dict memory usage can grow in steps.
Shallow copy (copy.copy() or list[:]): creates a new container but nested objects are still shared
references.
Deep copy (copy.deepcopy()): recursively creates
new objects for all nested elements. Fully independent.
import copy
a = [[1,2],[3,4]]
b = copy.copy(a)
b[0][0] = 99 # also changes a[0][0]!
c = copy.deepcopy(a)
c[0][0] = 99 # a is unchanged
A concise way to create lists: [expression for item in iterable if condition]. They're generally faster
than equivalent for-loops because the iteration is implemented in C.
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x%2==0]
flat = [n for row in matrix for n in row]
Use comprehensions for simple transformations. Use generator expressions (x for x in ...) for large data to avoid building the full list in
memory.
The GIL is a mutex that prevents multiple native threads from executing Python bytecode simultaneously in CPython. Only one thread runs Python code at a time, even on multi-core CPUs.
Impact: CPU-bound multi-threaded Python programs don't get
true parallelism. Workarounds: use multiprocessing
(separate processes, separate GIL), or use async/await for I/O-bound tasks. The GIL is released during
I/O and C extensions.
In Python 2: range() returned a list; xrange() returned a lazy iterator (memory efficient). In Python
3: xrange() is removed and range() behaves like the old xrange() — it's a lazy, memory-efficient sequence object that generates
values on demand.
r = range(1_000_000) # O(1) memory — no list created
print(r[999999]) # instant random access
Python automatically interns (caches) short strings that look like identifiers (no spaces, all
alphanumeric). This means two variables with the same interned string point to the same
object in memory — so is returns True.
a = "hello"; b = "hello"
a is b # True — interned
c = "hello world"; d = "hello world"
c is d # False — not interned (has space)
A set is an unordered collection of unique, hashable elements backed by a hash table.
Use sets when: (1) you need fast membership testing (in is O(1)),
(2) you need to remove duplicates from a sequence, (3) you need set operations (union, intersection,
difference).
s = {1,2,3,2,1} # {1, 2, 3}
dedup = list(set(lst)) # remove duplicates
99 in s # O(1) lookup
append(x)— adds x as a single element (even if x is a list)extend(iterable)— adds each element of the iterable individually+— creates a new list; does not modify either operand
a = [1,2]
a.append([3,4]) # [1, 2, [3, 4]]
a.extend([5,6]) # [1, 2, [3, 4], 5, 6]
b = a + [7] # new list; a unchanged
Use try/except/else/finally. finally always executes (even if an exception occurred or return was called) — used for cleanup (closing files, DB connections).
try:
result = risky_operation()
except ValueError as e:
print(f"Value error: {e}")
except (TypeError, KeyError):
print("Type or Key error")
else:
print("Success!") # only if no exception
finally:
cleanup() # always runs
map(fn, iterable) applies fn to every element (lazy). filter(fn, iterable) keeps elements where fn returns True (lazy). Both
return iterators — wrap with list() to get a list.
Prefer list comprehensions for readability. Use map() when passing an existing function (e.g. map(str.upper, words) — no lambda needed). Use map()/filter() when passing as
arguments or for lazy evaluation on large data.
OOP & Classes — Questions 16 to 25 Intermediate
class MyClass:
counter = 0
def instance_method(self): # has access to self (instance)
return self
@classmethod
def class_method(cls): # has access to class (cls)
return cls.counter
@staticmethod
def static_method(): # no access to self or cls
return "utility function"
Use classmethod as alternative constructors. Use staticmethod for utility functions that logically belong to the class but don't need class/instance state.
MRO defines the order Python looks up methods in a class hierarchy with multiple inheritance. Python uses the C3 linearisation algorithm (also called C3 superclass linearisation), which guarantees a consistent, predictable order.
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.mro()) # [D, B, C, A, object]
Rule: left-to-right, depth-first, but ensuring each class appears after all classes that depend on it.
Dunder methods (double-underscore: __method__) are special methods
that Python calls implicitly for built-in operations. Key ones:
__init__— constructor, called when creating an instance__repr__— unambiguous string representation (for debugging)__str__— human-readable string (called byprint())__eq__— equality comparison (==)__len__— called bylen()__getitem__— indexingobj[key]__enter__/__exit__— context manager (withstatement)
__new__ is called first — it creates and returns the new
object (allocates memory). __init__ is called second — it
initialises the already-created object (sets attributes). __new__ is a class method that receives cls; __init__ receives the
already-created self. You rarely need to override __new__ (only for immutable types or singletons).
Inheritance (IS-A): a class inherits behaviour from a parent. Use when the subclass truly is a specialised version of the parent.
Composition (HAS-A): a class contains instances of other classes as attributes. Preferred for most cases — more flexible, avoids tight coupling, easier to test.
Principle: "Prefer composition over inheritance". Use inheritance when there's a clear IS-A relationship and you want to use polymorphism.
A @property makes a method look like an attribute. It lets you add
validation or computation without changing the interface (encapsulation without getters/setters).
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self): return self._radius
@radius.setter
def radius(self, v):
if v < 0: raise ValueError
self._radius = v
Abstract classes (abc.ABC) define an interface that subclasses must
implement. You cannot instantiate an abstract class directly. Use @abstractmethod to declare methods that must be overridden.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
class Circle(Shape):
def area(self): return 3.14 * self.r**2
Polymorphism allows different objects to respond to the same interface/method call in their own way. Python uses duck typing — if an object has the right method, it works regardless of its class.
def make_sound(animal):
animal.speak() # works for Dog, Cat, Bird...
class Dog:
def speak(self): print("Woof")
class Cat:
def speak(self): print("Meow")
@dataclass (Python 3.7+) auto-generates __init__, __repr__, __eq__ from class annotations. Use for data-holding classes where you'd
otherwise write boilerplate.
from dataclasses import dataclass, field
@dataclass
class Point:
x: float
y: float
label: str = ""
p = Point(1.0, 2.0) # __init__ generated
print(p) # Point(x=1.0, y=2.0, label='')
Encapsulation is hiding internal state and exposing only necessary interfaces. Python uses convention not enforcement:
_name— single underscore: "by convention, private" (still accessible)__name— double underscore: name mangling to_ClassName__name(harder to access accidentally)- Use
@propertyfor controlled access with validation
Python's philosophy: "We're all adults here." Convention over enforcement.
Functional Programming — Questions 26 to 35 Intermediate
A decorator is a function that takes a function as input and returns a modified version. Used to add
behaviour (logging, timing, auth checks) without modifying the original function. Syntactic sugar for
f = decorator(f).
import functools, time
def timer(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
t0 = time.time()
result = fn(*args, **kwargs)
print(f"{fn.__name__}: {time.time()-t0:.3f}s")
return result
return wrapper
Always use @functools.wraps(fn) to preserve
the original function's metadata.
A generator is a lazy iterator that produces values on demand using yield. It uses O(1) memory regardless of sequence size — the entire
sequence is never built in memory.
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
gen = fibonacci()
print([next(gen) for _ in range(8)]) # [0,1,1,2,3,5,8,13]
Key: generators can represent infinite sequences. They resume
from where they left off on each next() call.
A closure is a function that "closes over" variables from its enclosing scope, even after that scope
has finished executing. The enclosing scope's variables are stored in the closure's __closure__ attribute.
def make_multiplier(n):
def multiplier(x):
return x * n # n from enclosing scope
return multiplier
double = make_multiplier(2)
print(double(5)) # 10 — n=2 is remembered
return terminates the function and sends a value back once. yield pauses the function, sends a value, and resumes from the same
point on the next next() call. A function with yield becomes a generator function — calling it returns a generator
object (not the result directly).
A lambda is a small, anonymous, single-expression function: lambda args: expression. Use for short functions passed to sorted(), map(), filter() or as callback arguments. For anything complex, use a named
def.
people = [("Alice",30),("Bob",25),("Carol",35)]
sorted(people, key=lambda p: p[1]) # sort by age
@lru_cache(maxsize=128) memoises a function's results — caches the
return value for each unique set of arguments. Subsequent calls with the same args return the cached
result instantly (O(1) instead of O(n)).
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
fib(100) # instant — O(n) total instead of O(2^n)
The with statement manages resources — it calls __enter__ on entry and __exit__ on
exit (even if an exception occurs). Guarantees cleanup without explicit try/finally.
with open("file.txt") as f:
data = f.read() # file closed automatically
# Custom context manager:
from contextlib import contextmanager
@contextmanager
def timer():
t0 = time.time()
yield
print(f"{time.time()-t0:.3f}s")
Iterable: any object with __iter__() that returns
an iterator (list, tuple, dict, str, generator). Can be looped over multiple times.
Iterator: an object with __iter__() AND __next__(). Stateful
— remembers current position. Can only be iterated once. Raises StopIteration when exhausted.
All iterators are iterables, but not all iterables are iterators. A list is
iterable but not an iterator. iter(some_list) returns a
list_iterator.
functools.partial(fn, *args, **kwargs) creates a new function with
some arguments pre-filled. Useful for creating specialised versions of general functions.
from functools import partial
def power(base, exp): return base ** exp
square = partial(power, exp=2)
cube = partial(power, exp=3)
print(square(5)) # 25
Type hints (PEP 484) annotate variables, function parameters, and return types with expected types. They're not enforced at runtime by Python — they're for static analysis (mypy, pyright), IDE autocompletion, and documentation.
from typing import Optional, Union
def greet(name: str, age: Optional[int] = None) -> str:
return f"Hello {name}"
Advanced Python — Questions 36 to 50 Advanced
CPython uses reference counting as the primary mechanism: every object has a counter of how many references point to it. When it reaches 0, the object is immediately deallocated.
Reference counting cannot handle circular references (A → B →
A). For this, Python has a cyclic garbage collector (the gc module) that periodically detects and breaks cycles. You can trigger
it with gc.collect().
async/await enables asynchronous programming —
running other code while waiting for I/O operations (network, files, DB). It's single-threaded
concurrency using an event loop (asyncio).
import asyncio
async def fetch_data(url):
await asyncio.sleep(1) # non-blocking wait
return {"data": url}
async def main():
results = await asyncio.gather(
fetch_data("url1"),
fetch_data("url2"), # both run concurrently!
)
Use for I/O-bound tasks (APIs, databases). For CPU-bound, use multiprocessing.
A metaclass is the "class of a class" — it defines how a class itself is created. Just as a class
creates instances, a metaclass creates classes. The default metaclass in Python is type.
Metaclasses are used for: ORMs (like Django models), API frameworks (validation), enforcing class structure, singleton pattern. Interview tip: "We use metaclasses in Django to make Model classes work magically."
threading: multiple threads within one process, share the same memory. Limited by GIL for CPU-bound tasks, but good for I/O-bound tasks.
multiprocessing: multiple separate processes, each with its
own memory and GIL. True parallelism for CPU-bound tasks. Higher overhead (spawning processes),
inter-process communication via Queue/Pipe.
A descriptor is any class that implements __get__, __set__, and/or __delete__. Used as
class attributes to intercept attribute access. @property is the
most common descriptor. Django fields, SQLAlchemy columns, and classmethod/staticmethod are all
descriptors.
By default, Python stores instance attributes in a __dict__ per
instance. __slots__ replaces this with a fixed-size array, reducing
memory (no per-instance dict overhead) and slightly improving attribute access speed.
class Point:
__slots__ = ["x", "y"] # no __dict__; ~40% less memory
def __init__(self, x, y):
self.x = x; self.y = y
Use when creating millions of instances of the same class (data science, simulations).
__repr__: unambiguous, developer-facing. Should ideally return a
string that can recreate the object: eval(repr(obj)) == obj. Called
by repr() and in the REPL.
__str__: human-readable, user-facing.
Called by str() and print().
Falls back to __repr__ if not defined.
Rule: always define __repr__. Define __str__ only when you need a different, friendlier display.
Monkey patching is dynamically replacing or extending methods/attributes of a class or module at runtime, without modifying the source code. Used in testing (mocking), hotfixes, and extending third-party libraries.
import some_library
def my_fixed_method(self): return "fixed"
some_library.SomeClass.method = my_fixed_method
@classmethod is the right choice for factory methods because it
receives cls — so it works correctly with subclasses (creates an
instance of the subclass, not the parent).
class Date:
def __init__(self, y, m, d): ...
@classmethod
def from_string(cls, s):
y,m,d = s.split("-")
return cls(int(y),int(m),int(d)) # cls, not Date
A namedtuple is an immutable, lightweight alternative to a class
for simple data — like a tuple but with named fields. Memory-efficient (uses __slots__), supports unpacking, and works in sets and as dict keys.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
print(p.x, p.y) # named access
x, y = p # unpacking
| Operation | List | Dict/Set | Deque |
|---|---|---|---|
| Append (end) | O(1) | O(1) insert | O(1) |
| Insert (middle) | O(n) | — | O(n) |
| Lookup by index | O(1) | O(1) by key | O(n) |
in membership |
O(n) | O(1) | O(n) |
| Delete (end) | O(1) | O(1) | O(1) |
| Delete (middle) | O(n) | — | O(n) |
defaultdict(factory) — like a dict but returns a default value
(from factory) for missing keys instead of raising KeyError.
Counter(iterable) — counts occurrences of elements, returns a
dict-like object with counts. Has useful methods like most_common().
from collections import defaultdict, Counter
dd = defaultdict(list)
dd["a"].append(1) # no KeyError
c = Counter("mississippi")
c.most_common(2) # [('i',4), ('s',4)]
Python's tuple unpacking makes this elegant. The right side is evaluated as a tuple first, then unpacked to the left side:
a, b = 10, 20
a, b = b, a # swaps in one line
print(a, b) # 20 10
The walrus operator (:=, Python 3.8+) assigns a value to a variable
as part of an expression. Avoids computing a value twice:
# Without walrus — compute twice:
if re.search(pattern, text):
m = re.search(pattern, text)
# With walrus — compute once:
if m := re.search(pattern, text):
print(m.group())
Several approaches:
# Method 1: Override __new__
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
# Method 2: Module-level instance (Pythonic)
# singleton.py → create instance once, import everywhere
# Method 3: @functools.cache on a factory function
Common Coding Patterns Coding
These patterns appear in almost every Python coding interview. Master them:
# ── 1. Two Sum — dict for O(n) ────────────────────────
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
complement = target - n
if complement in seen:
return [seen[complement], i]
seen[n] = i
# ── 2. Reverse a string ───────────────────────────────
print("hello"[::-1]) # "olleh" — slice trick
print("".join(reversed("hello"))) # "olleh"
# ── 3. Check palindrome ───────────────────────────────
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
# ── 4. FizzBuzz ───────────────────────────────────────
for i in range(1, 101):
print("FizzBuzz" if i%15==0 else "Fizz" if i%3==0 else "Buzz" if i%5==0 else i)
# ── 5. Flatten nested list ────────────────────────────
def flatten(lst):
return [x for sub in lst
for x in (flatten(sub) if isinstance(sub, list) else [sub])]
# ── 6. Most frequent element ──────────────────────────
from collections import Counter
def most_frequent(lst):
return Counter(lst).most_common(1)[0][0]
# ── 7. Binary search ──────────────────────────────────
def binary_search(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == target: return mid
elif arr[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1
# ── 8. Anagram check ──────────────────────────────────
def is_anagram(s1, s2):
return Counter(s1.lower()) == Counter(s2.lower())
Practice Python Online — Free Compilers
Practice coding patterns and interview questions directly in your browser. No installation required.
Click each option to check your answer. These are real-interview-style questions covering all topics from this chapter.
type([])?len("Python") return?[1,2,3][-1]?{} create in Python?bool(0), bool(""), bool([]), bool(None)?yield return when called?
x in {1,2,3} (set
membership)?deepcopy() function?
"hello"[::2]?@functools.wraps(fn) do inside a
decorator?async/await for
concurrent execution?collections class returns a default value for
missing keys?zip([1,2,3], ['a','b','c']) produce?
__slots__ do in a Python class?- Most-asked basics: mutable vs immutable, list vs tuple vs set vs dict,
isvs==, LEGB scope, mutable default arg trap, shallow vs deep copy. - OOP essentials: all four pillars (encapsulation, inheritance, polymorphism, abstraction), MRO, dunder methods, classmethod vs staticmethod, property, abstract classes.
- Functional must-knows: decorators with
@functools.wraps, generators withyield, closures, lambda, list comprehensions vsmap/filter,lru_cache. - Advanced topics: GIL and its workarounds, reference counting + GC, async/await for I/O,
__slots__, metaclasses, walrus operator, descriptors. - Data structures: know time complexities — set/dict lookups are O(1); list
inis O(n); useCounter,defaultdict,deque. - Coding patterns: two-sum with dict, two-pointer, sliding window, binary search, BFS/DFS with collections.deque, recursion with memoisation.
- Soft skills matter: always explain your approach before coding; mention time and space complexity; discuss trade-offs; test with edge cases (empty, single element, duplicates).
- Practice: LeetCode (Easy → Medium in Python), HackerRank Python track, and mock interviews. Read Python's official documentation and PEPs for deep answers.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.