Python interview questions and answers: 25 questions and 5 coding tasks
These Python interview questions run from basic to advanced, each with a short correct answer and code where it helps. After them come five Python coding interview questions with solutions, and how to think aloud while you solve them.
What are the basic Python interview questions?
Basic Python interview questions check data types, mutability, functions, comprehensions, copying, and the with statement. Expect them in the first round and for junior roles. Every Python interview questions and answers list starts here. All code is Python 3.
1. Which built-in data types does Python have?
Numbers (int, float, complex, bool), text (str), binary (bytes), sequences (list, tuple, range), dict, set and frozenset, and None.
2. What is the difference between a list and a tuple?
Lists are mutable and tuples are not. Tuples can be dictionary keys if everything inside is hashable. A tuple can still hold a mutable object, and that object can change:
t = (1, [2])
t[1].append(3)
print(t) # (1, [2, 3])
3. What does mutable mean, and why does it matter?
A mutable object can change in place. Two names can point to the same object, so a change through one name shows up in the other.
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3]
4. What is the difference between == and is?
== compares values by calling __eq__. is checks whether two names refer to the same object. Use is for None (if x is None). Never use it to compare numbers or strings.
5. What is the mutable default argument trap?
Default values are built once, when the function is defined. A default list is shared by every call.
def add(item, bucket=[]):
bucket.append(item)
return bucket
print(add(1), add(2)) # [1, 2] [1, 2]
def add_fixed(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
6. What do *args and **kwargs do?
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dict. At a call site, the same symbols unpack a sequence or a dict into arguments.
7. What are list, dict and set comprehensions?
A short way to build a collection from an iterable, with an optional filter.
squares = [x * x for x in range(5) if x % 2 == 0] # [0, 4, 16]
lengths = {w: len(w) for w in ["a", "bb"]} # {'a': 1, 'bb': 2}
mods = {x % 3 for x in range(10)} # {0, 1, 2}
8. What is the difference between a shallow copy and a deep copy?
A shallow copy (list.copy(), copy.copy()) makes a new outer container but shares the inner objects. copy.deepcopy() copies everything recursively.
import copy
data = [[1], [2]]
shallow = data.copy()
deep = copy.deepcopy(data)
data[0].append(9)
print(shallow) # [[1, 9], [2]]
print(deep) # [[1], [2]]
9. What does the with statement do?
It runs setup and cleanup around a block using a context manager (an object with __enter__ and __exit__). The cleanup runs even if the block raises. Files, locks and database connections use it.
What are intermediate Python interview questions?
This is where mid-level interviews spend their time.
10. What is a decorator?
A function that takes a function and returns a new one, applied with @. Use functools.wraps so the wrapped function keeps its name and docstring.
import functools, time
def timer(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
print(f"{fn.__name__} took {time.perf_counter() - start:.4f}s")
return wrapper
@timer
def work(n):
return sum(range(n))
11. What is a generator, and why use one?
A function with yield returns an iterator that produces values one at a time and keeps its state between them. It uses constant memory, which suits large or endless streams.
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(3))) # [3, 2, 1]
A generator expression, (x * x for x in range(3)), is the lazy form of a list comprehension.
12. What is the difference between an iterable and an iterator?
An iterable has __iter__ and can give you an iterator. An iterator has __next__, returns one item per call and raises StopIteration at the end. A list is iterable but not an iterator. You can loop over it many times, while an iterator is used up after one pass.
13. How does variable scope work (LEGB)?
Python looks up a name in Local, Enclosing function, Global, then Built-in scope. Assigning inside a function makes the name local unless you declare it global or nonlocal.
def outer():
count = 0
def inner():
nonlocal count
count += 1
return count
return inner
f = outer()
print(f(), f()) # 1 2
14. What is a closure, and what is the late-binding gotcha?
A closure is an inner function that remembers variables from its enclosing function. Closures look up the variable when called, not when defined:
fs = [lambda: i for i in range(3)]
print([f() for f in fs]) # [2, 2, 2]
fs = [lambda i=i: i for i in range(3)]
print([f() for f in fs]) # [0, 1, 2]
15. What is the difference between @staticmethod, @classmethod and a normal method?
A normal method receives the instance (self). A class method receives the class (cls), which suits alternative constructors. A static method receives nothing extra and is a plain function that lives in the class namespace.
16. How do you handle exceptions properly?
Catch specific exceptions, not bare except:. Use else for code that runs only when nothing was raised, and finally for cleanup. Use raise ... from err to keep the original cause when you wrap an error.
17. What are the common problems with floating-point numbers?
Floats are binary approximations, so 0.1 + 0.2 == 0.3 is False. Compare with math.isclose, or use decimal.Decimal for money.
What are advanced Python interview questions?
Senior interviews push on how Python works underneath.
18. What is the GIL?
The Global Interpreter Lock lets only one thread run Python bytecode at a time in standard CPython. Threads still help with I/O-bound work, because the lock is released while waiting. For CPU-bound work, use multiprocessing, native extensions, or a task queue. Free-threaded builds have existed since 3.13 and are officially supported (still optional, not the default) from 3.14 (Python 3.14 release notes, checked November 2026).
19. Threads, processes or asyncio: how do you choose?
Use asyncio for many concurrent network calls in one thread. Use threads for blocking I/O when the libraries are not async. Use processes for CPU-bound work. Each process has its own interpreter and memory, so sharing data costs more.
20. How does Python manage memory?
CPython counts references to each object and frees it when the count reaches zero. A cyclic garbage collector finds groups of objects that only reference each other. sys.getrefcount(obj) shows the count, always one higher than you expect because the call itself holds a reference.
21. What are __slots__ and when do they help?
Declaring __slots__ = ("x", "y") replaces the per-instance __dict__ with fixed fields. This saves memory when you create very many small objects, and it blocks adding new attributes.
22. How does inheritance work, and what is the MRO?
Python supports multiple inheritance. The method resolution order (MRO) is the order in which classes are searched, computed with C3 linearization. super() follows the MRO. You can print it with ClassName.__mro__.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def speak(self):
return f"{self.name} says woof"
print(Dog.__mro__) # (Dog, Animal, object)
23. What does making an object hashable require?
It needs __hash__ and an __eq__ that agree: equal objects must have equal hashes. If you define __eq__ without __hash__, Python sets __hash__ to None and instances become unhashable. Only use immutable fields in the hash.
24. What are dataclasses and type hints?
@dataclass generates __init__, __repr__ and __eq__ from annotated fields. Type hints are not enforced at run time. Tools like mypy check them, and they document intent.
25. How do you test Python code?
Use pytest (or unittest). Keep tests small, name the behavior, and cover edge cases. Use pytest.mark.parametrize for many inputs and unittest.mock to replace slow or external parts.
import pytest
@pytest.mark.parametrize("nums, target, expected", [([2, 7, 11, 15], 9, [0, 1]), ([3, 3], 6, [0, 1])])
def test_two_sum(nums, target, expected):
assert two_sum(nums, target) == expected
What are common Python coding interview questions?
These five Python coding interview questions come up in many forms. Each solution was run before it went on this page. State the complexity after you code.
Task 1: Two sum
Given a list of numbers and a target, return the indices of two numbers that add up to the target.
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
need = target - n
if need in seen:
return [seen[need], i]
seen[n] = i
return []
One pass with a dict. O(n) time, O(n) space. The brute-force version is O(n²), so mention it first and then improve it.
Task 2: Group anagrams
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w)
return list(groups.values())
# ["eat","tea","tan","ate","nat","bat"]
# -> [["eat","tea","ate"], ["tan","nat"], ["bat"]]
The sorted letters are the key. O(n · k log k) for n words of length k.
Task 3: Valid parentheses
def is_valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stack
A stack, O(n). Test "((" (leftovers), "(]" (mismatch) and "" (valid).
Task 4: Merge intervals
def merge(intervals):
out = []
for start, end in sorted(intervals):
if out and start <= out[-1][1]:
out[-1][1] = max(out[-1][1], end)
else:
out.append([start, end])
return out
# [[1,3],[8,10],[2,6],[15,18]] -> [[1,6],[8,10],[15,18]]
Sort, then extend or start a new interval. O(n log n). Ask whether touching intervals such as [1,4] and [4,5] should merge. This code merges them.
Task 5: LRU cache
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key)
return self.data[key]
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.capacity:
self.data.popitem(last=False)
Both operations are O(1). Some interviewers want a hand-built hash map plus doubly linked list instead, so say you know that version and offer to write it.
Python interview questions by experience and role
The same list serves every level, but the weight changes.
| Candidate | Focus |
|---|---|
| Freshers | Questions 1 to 9 and tasks 1 to 3. Run every snippet yourself and explain it in plain words. |
| 5 years of experience | Questions 10 to 25, plus a project you can defend: design choices, tests, profiling with cProfile, and one bug you debugged. |
| Data analyst | Python basics first, then pandas: merge, groupby, handling missing values with isna, fillna and dropna, and why vectorized operations beat row loops. Pair with SQL interview questions. |
| Data engineer | Generators for large files, memory use, concurrency (questions 18 and 19), testing, and SQL. |
How do you think aloud in a Python coding round?
- Restate the problem and ask about input size, duplicates, empty input and sorted order.
- Give the simple solution first, with its cost. Then say what you would improve.
- Name your data structure and why: "I want constant-time lookup, so a dict."
- Write while talking, in small pieces, using clear names.
- Trace one example by hand, then try an edge case such as an empty list.
- State time and space at the end.
Silence is the common mistake. Interviewers cannot score reasoning they cannot hear. More on this in live coding interview tips, and for the whole loop see technical interview tips.
If you get stuck mid-answer
Practice is the best fix. Type each task above from memory until you can explain it without looking, and no tool replaces that. Hintly is a desktop app for Mac and Windows that listens during a live interview and shows a suggested answer in a small overlay, built from your own notes such as your CV or resume. A keyboard shortcut answers what is on your screen, such as a coding problem. The overlay is hidden from screen share. It is pre-launch, so you can join the waitlist. Check any rules an employer has about tools in interviews first. More in our AI coding interview assistant guide. For other languages, see the Java interview questions post.
Questions
How can I prepare for a Python interview?
Explain the core ideas in your own words (mutability, iterators, the GIL, scope), then solve coding tasks on a blank editor without autocomplete. Say your reasoning out loud. Reading answers is not enough; type the code and run it.
What is the 80/20 rule in Python?
It is the Pareto idea, not a language feature. In interviews, a small core of Python (core types, comprehensions, functions, classes, exceptions, the standard library) covers most questions. In performance work, most run time sits in a small part of the code, so profile with cProfile before you optimize.
What are the top 50 Python interview questions?
Most 50-question lists repeat the same core ideas in different words. The 25 questions and 5 tasks here cover the core ideas such lists repeat. Add string methods, file handling, virtual environments, packaging, and pandas basics if the job is in data.
What are basic Python skills?
Data types, control flow, functions, lists, dicts and sets, comprehensions, classes, exceptions, reading and writing files, modules and imports, and running code with a virtual environment. Add pytest and one library the job names.
Which built-in data structures matter most?
List, dict, set and tuple, plus collections.deque, Counter and defaultdict. Dict and set lookups are O(1) on average, list lookups by value are O(n), and popping from the front of a list is O(n).
Are Python interviews mostly algorithms?
It depends on the role. Backend and general software roles mix language questions with data structure tasks. Data roles add pandas and SQL. Ask the recruiter what the rounds cover.