40 Python Interview Questions and Answers (Beginner to Advanced)
· updated

Python is the most common language in coding interviews, for back-end, data, machine learning, automation and QA roles. The good news is that the questions repeat. Interviewers keep coming back to the same handful of concepts, because they quickly show whether you actually understand the language or have only used it.
The short answer: Python interviews usually cover five areas:
- Basics: data types, mutability, lists vs tuples, dictionaries and sets.
- Functions: arguments,
*argsand**kwargs, scope, lambdas and the mutable default trap. - Object-oriented Python: classes, inheritance, dunder methods and decorators like
@property. - Advanced features: generators, iterators, decorators, context managers and the GIL.
- Coding tasks: short problems like reversing a string, finding duplicates or counting words.
The 40 questions below cover all five, with short answers and code you can say out loud.
Basics
1. What are Python’s main built-in data types?
Numbers (int, float, complex), str, bool, list, tuple, dict, set, frozenset, bytes and NoneType.
2. What’s the difference between a list and a tuple?
Lists are mutable (you can change them after creation) and tuples are immutable. Tuples are slightly faster and smaller, can be used as dictionary keys if their contents are hashable, and signal “this shouldn’t change”. Use lists for collections that grow or change and tuples for fixed records like coordinates.
3. What do mutable and immutable mean?
A mutable object can be changed in place (lists, dicts, sets). An immutable one can’t; any “change” creates a new object (ints, floats, strings, tuples, frozensets).
4. How is a dictionary implemented, and why are lookups fast?
A dictionary is a hash table. Python hashes the key to find where the value is stored, so lookups, inserts and deletes are O(1) on average. That’s why keys must be hashable (immutable). Since Python 3.7, dictionaries also keep insertion order.
5. What’s the difference between == and is?
== checks whether two values are equal. is checks whether they’re the same object in memory. Use is only for singletons like None: if x is None.
6. What is a set, and when would you use one?
An unordered collection of unique, hashable items. Use it to remove duplicates or for fast membership checks: x in my_set is O(1) on average, while x in my_list is O(n).
7. What are list comprehensions?
A short way to build a list from an iterable:
squares = [n * n for n in range(10) if n % 2 == 0]
There are also dict comprehensions ({k: v for ...}), set comprehensions and generator expressions with round brackets.
8. How does slicing work?
seq[start:stop:step]. stop is excluded, negative numbers count from the end, and s[::-1] reverses a sequence.
9. What’s the difference between append() and extend()?
append(x) adds x as a single item. extend(iterable) adds each item from the iterable.
10. What’s the difference between a shallow and a deep copy?
A shallow copy (copy.copy(), list.copy(), lst[:]) creates a new outer object but shares the inner objects. A deep copy (copy.deepcopy()) copies everything recursively. With nested lists, changing an inner list affects a shallow copy but not a deep one.
Functions
11. What are *args and **kwargs?
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary.
def log(message, *args, **kwargs):
print(message, args, kwargs)
log("hi", 1, 2, level="info") # hi (1, 2) {'level': 'info'}
12. What’s wrong with this function?
def add_item(item, items=[]):
items.append(item)
return items
The default list is created once, when the function is defined, and shared between calls. add_item(1) then add_item(2) returns [1, 2]. The fix:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
This is probably the single most asked Python trick question.
13. What is a lambda?
A small anonymous function written in one expression: lambda x: x * 2. Mostly used as a short argument, for example sorted(users, key=lambda u: u.age).
14. Explain Python’s scope rules (LEGB).
Python looks up names in this order: Local, Enclosing function, Global (module), Built-in. Use global or nonlocal to assign to a name in an outer scope.
15. Are arguments passed by value or by reference?
Neither, exactly. Python passes references to objects (“pass by object reference”). If the function changes a mutable object in place, the caller sees it. If it reassigns the name, the caller doesn’t.
16. What do map(), filter() and zip() do?
map(f, xs) applies f to each item, filter(f, xs) keeps items where f is true, zip(a, b) pairs items from several iterables. All return lazy iterators.
17. What is a closure?
A function that remembers variables from the enclosing function that created it, even after that function has returned.
def multiplier(n):
def times(x):
return x * n
return times
double = multiplier(2)
double(5) # 10
Object-oriented Python
18. What’s the difference between a class and an instance?
A class is the blueprint; an instance is an object made from it. Class attributes are shared by all instances; instance attributes (set on self) belong to one object.
19. What is self?
The first parameter of an instance method, referring to the object the method was called on. Python passes it automatically.
20. What does __init__ do?
It initialises a new instance after it’s created, setting its starting attributes. (__new__ actually creates the object, but you rarely need it.)
21. What are dunder (magic) methods?
Methods with double underscores that let your classes work with Python’s built-in behaviour: __str__ and __repr__ for printing, __len__ for len(), __eq__ for ==, __iter__ for loops, __enter__ and __exit__ for with.
22. What’s the difference between @staticmethod and @classmethod?
A classmethod receives the class (cls) as its first argument and is often used for alternative constructors. A staticmethod receives nothing automatic; it’s just a function grouped inside the class.
23. How does inheritance work, and what is super()?
A child class inherits attributes and methods from its parent and can override them. super() calls the parent’s version, usually in __init__. With multiple inheritance, Python follows the method resolution order (MRO), which you can see with ClassName.__mro__.
24. What does @property do?
It lets you expose a method as an attribute, so you can add validation or computed values without changing how callers use the class.
25. What are dataclasses?
A decorator (@dataclass) that generates __init__, __repr__ and __eq__ for classes that mainly hold data, saving boilerplate.
Advanced features
26. What is a generator?
A function that uses yield to produce values one at a time, pausing between them. Generators are lazy, so they use very little memory for large or infinite sequences.
def countdown(n):
while n > 0:
yield n
n -= 1
27. What’s the difference between an iterable and an iterator?
An iterable is anything you can loop over (it has __iter__). An iterator is the object that does the looping, producing the next value with __next__ and raising StopIteration when it’s done. A list is iterable; iter(list) gives you an iterator.
28. What is a decorator?
A function that takes a function and returns a new one, adding behaviour around it without changing its code.
import functools, time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
return result
return wrapper
29. What is a context manager?
An object used with with that sets something up and guarantees cleanup, even if an error happens. with open("f.txt") as f: closes the file automatically. You can write one with a class (__enter__ and __exit__) or with @contextlib.contextmanager.
30. What is the GIL?
The Global Interpreter Lock in CPython allows only one thread to run Python bytecode at a time. Threads still help with I/O-bound work (network, files) but not CPU-bound work, where you’d use multiprocessing or libraries written in C. Python 3.13 introduced an optional free-threaded build without the GIL.
31. Threading vs multiprocessing vs asyncio?
- Threading: good for waiting on I/O; limited by the GIL for CPU work.
- Multiprocessing: separate processes, true parallelism for CPU-heavy work, more memory.
- asyncio: a single thread handling many I/O tasks with
asyncandawait; great for lots of network calls.
32. How does Python manage memory?
Mainly through reference counting: an object is freed when nothing refers to it. A cyclic garbage collector cleans up groups of objects that refer to each other.
33. How do you handle exceptions?
try:
value = int(text)
except ValueError:
value = 0
else:
print("parsed fine")
finally:
print("always runs")
Catch specific exceptions rather than a bare except:.
34. What are type hints?
Optional annotations like def total(prices: list[float]) -> float:. Python doesn’t enforce them at runtime, but tools like mypy and your editor use them to catch bugs.
Coding tasks
35. Reverse a string
def reverse(s: str) -> str:
return s[::-1]
36. Check whether a string is a palindrome
def is_palindrome(s: str) -> bool:
cleaned = "".join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]
37. Find duplicates in a list
def duplicates(items):
seen, dupes = set(), set()
for x in items:
if x in seen:
dupes.add(x)
seen.add(x)
return list(dupes)
O(n) time, using sets for fast lookups.
38. Count word frequency
from collections import Counter
def top_words(text, n=3):
return Counter(text.lower().split()).most_common(n)
Mention collections (Counter, defaultdict, deque); interviewers like candidates who know the standard library.
39. Two sum
Return the indexes of two numbers that add up to a target.
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
return []
O(n) with a dictionary, instead of O(n²) with two loops.
40. Flatten a nested list
def flatten(items):
for x in items:
if isinstance(x, list):
yield from flatten(x)
else:
yield x
list(flatten([1, [2, [3, 4]], 5])) # [1, 2, 3, 4, 5]
How to prepare
- Say the answers out loud. Knowing something and explaining it clearly are different skills.
- Write code without autocomplete. Practise in a plain editor so you’re comfortable in a shared online one.
- Do 20 to 40 practice problems on a coding site, mostly easy and medium. See best websites to practise coding.
- Always state complexity. After each solution, say its time and space complexity.
- Learn the area you’re applying for. Back-end roles add Django or FastAPI; data roles add pandas and SQL interview questions; QA roles add pytest.
- Talk while you code. How to ace your technical interview covers how to structure a live coding round.
Get past the resume screen
Python roles vary a lot: one listing wants Django and PostgreSQL, the next wants pandas and Airflow, another wants pytest and Selenium. Your resume should lead with the parts of your Python experience each listing names. Tailr is a Chrome extension that tailors your resume to the job you’re viewing, using only your real experience, and writes a matching cover letter. Try Tailr on your next Python application.
Conclusion
Python interviews test a predictable set of ideas: data types and mutability, functions and the mutable default trap, classes and dunder methods, generators, decorators, context managers and the GIL, plus a few short coding problems. Learn the 40 questions above well enough to explain them without notes, practise writing code by hand, always mention complexity, and add the libraries that matter for the specific role.
Frequently asked questions
01What are the most common Python interview questions?
The most common are the difference between lists and tuples, mutable vs immutable types, how dictionaries work, list comprehensions, *args and **kwargs, the mutable default argument trap, generators and yield, decorators, shallow vs deep copy, the GIL, and short coding tasks like reversing a string, finding duplicates or counting words.
02How should I prepare for a Python interview?
Revise the core data types and their methods, practise writing small functions by hand without autocomplete, solve 20 to 40 easy and medium coding problems in Python, and be ready to explain time complexity. Read through the questions in this guide and say the answers out loud, then practise on a coding site under a time limit.
03Is Python enough to get a job?
Python alone is rarely enough; employers want Python plus the area you'll use it in. For back-end roles that means a framework like Django or FastAPI, SQL and APIs. For data roles, pandas, SQL and statistics. For automation and QA, testing frameworks like pytest. For machine learning, NumPy, scikit-learn and PyTorch.
04What Python questions are asked for freshers?
Freshers usually get questions on data types, lists vs tuples, dictionaries and sets, loops and conditionals, functions and arguments, string manipulation, basic OOP (classes, inheritance), exception handling, and simple coding tasks like checking for a palindrome, FizzBuzz, finding the largest number in a list or counting characters.
05What is the GIL in Python?
The Global Interpreter Lock is a lock in CPython, the standard Python interpreter, that lets only one thread run Python bytecode at a time. It means threads don't speed up CPU-heavy work, though they still help with waiting on input and output. For CPU-heavy tasks you use multiprocessing or libraries that release the GIL. Newer Python versions offer an optional build without the GIL.
06Do Python interviews include coding on a whiteboard?
Many include a live coding round, now usually in a shared online editor rather than on a whiteboard. You'll be asked to solve one or two problems while explaining your thinking. Interviewers care about clear, working code, sensible names, handling edge cases and being able to discuss time and space complexity.