I've put together a series of posts with my personal database of Python interview questions. It's not perfect, it's not complete, and no, there aren't any answers included. Some of the questions might even feel a little odd or out there. But in my experience, they're great at helping you figure out who's really ready for the job.
The series is split into three parts based on experience level:
- Python Interview Questions for Beginners (Junior)
- Python Interview Questions for Mid-Level Developers
- Python Interview Questions for Experienced Developers (Senior)
Got a question you think should be here? Or something you always ask in interviews? Let me know—I'd love to hear your thoughts!
What "middle" means here
Let's define the levels first. The way I see it: junior knows the syntax, middle knows what breaks in production, senior knows what not to build.
Some questions have a note under them about what I'm listening for. If you're the one interviewing, that's where to dig. If you're preparing, that's what separates a strong answer from a memorized one, and what the person on the other side of the table usually wants to hear.
Questions
1. Python Language Concepts
Q: What is the output of -12 % 10?
Q: What is the output of -12 // 10?
Q: What is the sequence of operators called in the expression a * b * c?
Q: Why shouldn't you use a mutable object (e.g., an empty list) as a default argument in Python?
Q: What does the id() function in Python do?
- Follow-up: Two equal strings can share the same
id(). Why?
Q: What are Python's comprehensions (list, dict, set)? When should you use them?
Q: Python 3.10 added structural pattern matching (match/case). How is it different from a chain of if/elif?
- Follow-up: What can
matchdestructure thatifcan't do cleanly?
Q: What is the yield keyword used for in Python?
Q: How do you differentiate between iterators and generators in Python?
- Bonus: Write an example of each.
Q: What is the difference between __iter__ and __next__ methods?
Q: How can you create a dictionary that preserves the order of key-value pairs?
Q: When would you use a dataclass over a NamedTuple, a TypedDict, or a plain class?
There's no wrong answer here, so it can't be memorized. I want to hear mutability weighed against hashability against runtime cost. And I want to hear that TypedDict isn't a class at all once the program is running.
- Follow-up: What does
frozen=Truebuy you, and what does it cost?
Q: Why would you use pathlib instead of os.path and string concatenation?
Q: What are try, except, else, and finally blocks? Provide examples.
2. Context Managers
Q: What is a context manager, and how does it differ from using try...finally?
try/finally does exactly the same job, so "it's more Pythonic" is a pretty dumb answer. What I'm waiting for is __enter__/__exit__ and the point behind them: you can reuse the manager. With try/finally you write it out again at every call site, until somebody eventually forgets.
Q: Which methods must be implemented to create a custom context manager class?
Q: Explain with blocks. Why are they considered more Pythonic than try-finally?
Q: Describe a use case where context managers can be helpful.
3. Async basics
Q: What is synchronous code, and how does it differ from asynchronous code?
Q: How do async functions differ from normal Python functions?
Q: What are async and await keywords in Python? Provide a simple example.
- Follow-up: What does
awaitdo, and when should it be used?
Q: What is the purpose of an event loop in Python, and how does the asyncio.run() function interact with it?
Q: How do you handle exceptions in asynchronous Python code?
Q: You need to call three independent async APIs. What's wrong with awaiting them one after another, and how would you fix it?
- Follow-up: One of the three fails. What happens to the other two?
Q: Can you explain the purpose of the async with and async for constructs? Provide examples.
Q: How can you perform file I/O asynchronously in Python?
Q: When would you choose async programming over multi-threading in Python?
4. Advanced Concepts
Q: What is the unittest module in Python? How to write tests in Python?
Q: Modern type hint syntax: what's the difference between List[int] and list[int], and between Optional[str] and str | None? Which would you write today?
Nothing hard here. The question just dates them: the answer shows which Python they've been writing for the last few years, and how much they keep up with best practices.
Q: Explain type checking in Python. Why is Python considered a strongly-typed language?
- Follow-up: Which static analysis tools would you put in CI, and in what order?
Q: How do you isolate Python code effectively (e.g., virtual environments)?
- Follow-up: What goes in
pyproject.toml, and what replacedsetup.pyfor you? - Follow-up: What's the difference between a lockfile and a requirements file, and when does that difference bite?
What this checks is the difference between intent and implementation. requirements.txt is what you chose yourself. The pinned transitive dependencies are what the resolver chose for you. pip freeze > requirements.txt erases that line: it dumps the whole graph into one file and no longer remembers which part was your call.
Q: How can you copy an object in Python? What's the difference between a shallow copy and a deep copy?
Pairs with the [[]] * 3 question further down. Same thing twice, and I'm curious whether they connect the two.
Q: How is memory managed in Python?
- Follow-up: Why does Python have a garbage collector, and how does it work?
Q: How can you share global variables across modules? Is it a good idea to do so?
Q: What is the __slots__ attribute in a class? What are its benefits and drawbacks?
By now everyone probably knows the benefits. The question is more about the drawbacks: no __dict__, no attributes you didn't declare, and inheritance stops being free.
Q: What are metaclasses in Python?
- Bonus: How can you create a class without using the class statement?
5. Coding Challenges
Q: How to check that one tuple contains all elements of another tuple?
Q: What will be the output of the following code?
>>> list = ['a', 'b', 'c', 'd', 'e']
>>> print(list[10:])
Q: How can I reload a previously imported module? (we assume that the module is a file module.py)
Q: What will be the output of the following code?
>>> a = [[]] * 3
>>> a[1].append(1)
>>> print(a)
Q: What's wrong with the following code?
def foo():
from .module import *
print(f"{bar()}")
Q: The file is located in /usr/lib/python/person.py. The program is run with python /usr/lib/python/person.py. What will the output be?
class Person:
def __init__(self, name):
__name__ = name
def getAge(self):
print(__name__)
p = Person("John")
p.getAge()
Q: Write a timeit decorator to measure the time of function execution.
Q: Write a decorator that will catch errors and repeat the function a maximum of 3 times (configurable).
Q: What's the output of the following code?
class parent:
def __init__(self, param):
self.v1 = param
class child:
def __init__(self, param):
self.v2 = param
obj = child(11)
print(obj.v1 + " " + obj.v2)
Q: Fix the following code to make it work.
class Repeater:
...
class RepeaterIterator:
...
repeater = Repeater("Hello")
for i in repeater:
print(i) # hello
Q: Write code to get unique values from a list of complex types (custom classes). Example: [A(1, "ab"), A(2, "ab"), A(2, "aa"), A(1, "ab")] -> [A(1, "ab"), A(2, "ab"), A(2, "aa")].
Q: We have the following code with the unknown function f(). In f(), we do not want to use a return, instead, we may want to use a generator.
for x in f(5):
print(x,)
The output looks like this:
0 1 8 27 64
Write a function f() so that we can have the output above.
Q: What's the output of the following code?
x = [[0], [1]]
print(len(' '.join(list(map(str, x)))))
Q: Write a function to generate all permutations of a string.
Q: Implement a basic LRU (Least Recently Used) Cache.