Python interview questions: answers with real output
Core language behavior and short coding tasks, each answered in plain words with code you can run.
Python interviews usually test how the language behaves (mutable vs immutable types, == vs is, copying, mutable default arguments, scope and closures), its idioms (comprehensions, generators, decorators, context managers) and short coding tasks such as two-sum, counting and flattening. Below are 21 questions from basic to advanced; every example was run and shows its real output.
Basic python interview questions
Basic1. What is the difference between a list and a tuple?
Lists are mutable: you can add, remove and change items. Tuples are immutable once created, which makes them usable as dictionary keys and a signal that the data should not change.
Pythonnums = [1, 2, 3]
nums.append(4)
print(nums)
point = (1, 2)
try:
point[0] = 5
except TypeError as e:
print('TypeError:', e)
print({point: 'ok'})Output (Python 3.12.10)[1, 2, 3, 4]
TypeError: 'tuple' object does not support item assignment
{(1, 2): 'ok'}Basic2. What is the difference between == and is?
== compares values; is checks whether two names point to the same object. Use is only for singletons such as None.
Pythona = [1, 2]
b = [1, 2]
print(a == b, a is b)
c = a
print(c is a)
x = None
print(x is None)Output (Python 3.12.10)True False True True
Basic3. What is wrong with a mutable default argument?
Default values are created once, when the function is defined, so a list default is shared between calls. Use None as the default and create the list inside the function.
Pythondef add_bad(item, items=[]):
items.append(item)
return items
print(add_bad('a'))
print(add_bad('b'))
def add_good(item, items=None):
items = [] if items is None else items
items.append(item)
return items
print(add_good('a'))
print(add_good('b'))Output (Python 3.12.10)['a'] ['a', 'b'] ['a'] ['b']
Basic4. What do *args and **kwargs do?
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. The same symbols unpack a sequence or dict when calling a function.
Pythondef show(*args, **kwargs):
print(args, kwargs)
show(1, 2, level='senior')
params = {'sep': ' | '}
print('a', 'b', **params)Output (Python 3.12.10)(1, 2) {'level': 'senior'}
a | bBasic5. What is the difference between a shallow copy and a deep copy?
A shallow copy creates a new outer container but shares the inner objects; a deep copy copies everything recursively. Changing a nested list affects a shallow copy but not a deep copy.
Pythonimport copy
original = [[1, 2], [3]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0].append(99)
print(shallow)
print(deep)Output (Python 3.12.10)[[1, 2, 99], [3]] [[1, 2], [3]]
Basic6. How do try, except, else and finally run?
try runs first. except runs only if a matching exception was raised. else runs only if no exception was raised. finally always runs, which makes it the place for cleanup.
Pythondef divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print('cannot divide by zero')
else:
print('result', result)
finally:
print('done')
divide(6, 3)
divide(1, 0)Output (Python 3.12.10)result 2.0 done cannot divide by zero done
Basic7. How do you count items in a list?
collections.Counter counts hashable items in one pass and gives you most_common(). For a manual version, use dict.get with a default.
Pythonfrom collections import Counter
words = ['sql', 'python', 'sql', 'excel', 'sql', 'python']
print(Counter(words).most_common(2))
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)Output (Python 3.12.10)[('sql', 3), ('python', 2)]
{'sql': 3, 'python': 2, 'excel': 1}Intermediate python interview questions
Intermediate8. What is the difference between a list comprehension and a generator expression?
A list comprehension builds the whole list in memory immediately. A generator expression produces items one at a time, only when asked, so it suits large or endless sequences.
Pythonsquares = [n * n for n in range(5)]
print(squares)
lazy = (n * n for n in range(5))
print(type(lazy).__name__)
print(next(lazy), next(lazy))
print(sum(n * n for n in range(1_000_000)))Output (Python 3.12.10)[0, 1, 4, 9, 16] generator 0 1 333332833333500000
Intermediate9. What does yield do?
yield turns a function into a generator: each call to next() runs the function until the next yield, returns that value and pauses, keeping local state between calls.
Pythondef fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
gen = fib()
print([next(gen) for _ in range(10)])Output (Python 3.12.10)[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Intermediate10. What is a decorator?
A decorator is a function that takes a function and returns a new one that wraps it, used for logging, caching, access checks or counting. functools.wraps keeps the original name and docstring.
Pythonimport functools
def count_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
@count_calls
def greet(name):
return f'hi {name}'
greet('a'); greet('b')
print(greet.__name__, greet.calls)Output (Python 3.12.10)greet 2
Intermediate11. What is a context manager?
A context manager defines what happens on entering and leaving a with block (__enter__ and __exit__), so cleanup runs even if an error occurs. Files, locks and database transactions use them.
Pythonclass Step:
def __init__(self, name):
self.name = name
def __enter__(self):
print('start', self.name)
return self
def __exit__(self, exc_type, exc, tb):
print('end', self.name, 'error' if exc_type else 'ok')
return True # swallow the error for this demo
with Step('load'):
print('working')
with Step('parse'):
raise ValueError('bad row')Output (Python 3.12.10)start load working end load ok start parse end parse error
Intermediate12. How do you solve two-sum in one pass?
Keep a dictionary of values already seen and their index. For each number, check whether target minus the number is in the dictionary. That is one pass, O(n) time, instead of checking every pair.
Pythondef two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return seen[target - n], i
seen[n] = i
return None
print(two_sum([3, 8, 11, 4], 12))
print(two_sum([1, 2], 9))Output (Python 3.12.10)(1, 3) None
Intermediate13. How do you sort by more than one key?
Pass a key function that returns a tuple. Python's sort is stable, so items that compare equal keep their original order.
Pythonpeople = [('Ava', 'eng', 150), ('Ben', 'eng', 120), ('Dev', 'sales', 95), ('Cara', 'eng', 120)]
by_team_then_pay = sorted(people, key=lambda p: (p[1], -p[2]))
for p in by_team_then_pay:
print(p)Output (Python 3.12.10)('Ava', 'eng', 150)
('Ben', 'eng', 120)
('Cara', 'eng', 120)
('Dev', 'sales', 95)Intermediate14. How do you check whether a string is a palindrome?
Normalize it (lowercase, letters and digits only), then compare it with its reverse using slicing [::-1].
Pythondef is_palindrome(s):
clean = ''.join(ch.lower() for ch in s if ch.isalnum())
return clean == clean[::-1]
print(is_palindrome('A man, a plan, a canal: Panama'))
print(is_palindrome('interview'))Output (Python 3.12.10)True False
Intermediate15. What is the GIL?
In CPython's standard build, the global interpreter lock lets only one thread execute Python bytecode at a time. Threads still help with I/O-bound work (network, disk), while CPU-bound work usually uses multiprocessing or native extensions. Python 3.13 added an optional, experimental free-threaded build without the GIL.
Advanced python interview questions
Advanced16. Why do lambdas in a loop all return the same value?
Closures capture variables, not values, and look them up when called (late binding). By then the loop has finished. Bind the current value with a default argument.
Pythonlate = [lambda: i for i in range(3)]
print([f() for f in late])
bound = [lambda i=i: i for i in range(3)]
print([f() for f in bound])Output (Python 3.12.10)[2, 2, 2] [0, 1, 2]
Advanced17. What is the difference between __str__ and __repr__?
__repr__ is the unambiguous developer view (used in the REPL, in lists and by repr()); __str__ is the readable view used by print() and str(). If only __repr__ is defined, str() falls back to it.
Pythonclass Money:
def __init__(self, cents):
self.cents = cents
def __repr__(self):
return f'Money({self.cents})'
def __str__(self):
return f'${self.cents / 100:.2f}'
m = Money(1999)
print(m)
print([m])Output (Python 3.12.10)$19.99 [Money(1999)]
Advanced18. What does @dataclass give you?
dataclasses generate __init__, __repr__ and __eq__ from type-annotated fields. frozen=True makes instances immutable and hashable; field(default_factory=list) avoids the shared mutable default problem.
Pythonfrom dataclasses import dataclass, field
@dataclass(frozen=True)
class Candidate:
name: str
skills: tuple = ()
@dataclass
class Team:
members: list = field(default_factory=list)
print(Candidate('Ava', ('sql',)))
print(Candidate('Ava') == Candidate('Ava'))
print(Team(), Team().members is Team().members)Output (Python 3.12.10)Candidate(name='Ava', skills=('sql',))
True
Team(members=[]) FalseAdvanced19. How do you flatten a nested list?
Recurse: for each item, yield from the flattened item if it is a list, otherwise yield the item. A generator keeps memory flat for large inputs.
Pythondef flatten(items):
for x in items:
if isinstance(x, list):
yield from flatten(x)
else:
yield x
print(list(flatten([1, [2, [3, 4]], [], 5])))Output (Python 3.12.10)[1, 2, 3, 4, 5]
Advanced20. How does memoization with lru_cache work?
functools.lru_cache stores results keyed by the arguments, so repeated calls return instantly. It turns the naive exponential Fibonacci into a linear one. Arguments must be hashable.
Pythonfrom 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(80))
print(fib.cache_info())Output (Python 3.12.10)23416728348467685 CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)
Advanced21. Why is checking membership in a set faster than in a list?
A set is a hash table, so x in s takes about the same time no matter how big the set is (O(1) in the typical case). A list is checked item by item (O(n)). Convert a list to a set first when you will test membership many times.
Pythonallowed = set(range(1_000_000))
print(999_999 in allowed)
print(type(allowed).__name__, len(allowed))Output (Python 3.12.10)True set 1000000
How to practice with this page
- Predict each example's output before reading it, then check.
- Solve the coding tasks yourself first, then state the time complexity.
- Practice in a plain editor if the interview uses one.
- Pair this page with SQL practice for data roles.
Related interview prep
Joins to window functions, with real output.
Open →QuestionsJavaScript interview questionsScope, closures and the event loop.
Open →RoleData scientist interview questionsRole-specific questions.
Open →MethodSTAR methodStructure answers about projects and problems you solved.
Open →Disclosure: TryHired makes HIRED, a paid job-search program, so we have a conflict of interest when we mention it. This question bank is free, with no TryHired signup.
Data roles: continue with data science and machine learning interview questions, with runnable NumPy examples.
Questions people ask
What Python questions are asked in interviews?
How should I prepare for a Python coding interview?
Which Python version do interviews use?
Do I need to know data structures and algorithms for a Python interview?
Is Python asked in data analyst interviews?
How this page is built
TryHired wrote these questions and answers. Every code block on this page was executed with Python 3.12.10 when the page was built, and the output shown is the real output; the build stops if any example fails. The question list is general practice: it does not predict what a particular employer will ask.
- Interviewers ask different questions for different roles and levels.
- Answers are short explanations, not complete language references.
- Python documentation, the Python tutorial: https://docs.python.org/3/tutorial/
- Python documentation, functools: https://docs.python.org/3/library/functools.html
- Python documentation, dataclasses: https://docs.python.org/3/library/dataclasses.html
- Python 3.13 release notes, free-threaded CPython: https://docs.python.org/3/whatsnew/3.13.html