Python interview questions: 10 with answers
10 Python interview questions with sample answers and tested code, from mutable defaults and is vs == to the GIL, plus how to explain them out loud.

On this page 11 sections ▾
TL;DR
- Wrong answers usually sound close to right, so each question pairs a common wrong answer with a strong one you can rehearse.
- Interviewers listen for the why behind an answer, so practice explaining each example, not just memorizing it.
- Know the standard library, since tools like
Counterandfunctools.wrapsanswer common follow-ups in a line or two.
If a Python interview is on your calendar, the questions that trip people up usually aren't about syntax at all. They're about how Python quietly handles objects behind the scenes, and these 10 Python interview questions are the ones worth practicing out loud. Every snippet below was tested on Python 3.13, so the output shown is real.
Quick facts
Python isn't named after the snake. Guido van Rossum was reading scripts from the BBC comedy Monty Python's Flying Circus when he started building it.
Python's usage among developers jumped 7 percentage points in a single year in Stack Overflow's 2025 Developer Survey.
The official Python FAQ warns that the default-argument bug in question 1 is one that commonly bites beginners.
Want to learn Python for the job you're after? Every ProCourse has an interactive Python level built around its field, so you learn it the way that field actually uses it, in a simulated terminal in your browser:
- SecuritySecurity Pro has a Python for Security level.
- DevOpsDevOps Pro has a Python for DevOps level.
- DataData Pro has a Python for Data level.
- AIAI Pro has a Python for AI level.
#1. Why does my default list keep growing?
This one looks like a typo and isn't. You're shown a function with a list as a default argument and asked what it prints on the second call. Python creates default values only once, when it defines the function, so every call that doesn't pass its own list shares the same one.
| 1 | def add_item(item, items=[]): |
| 2 | items.append(item) |
| 3 | return items |
| 4 | |
| 5 | print(add_item("a")) |
| 6 | print(add_item("b")) |
| 7 | |
| 8 | def add_item_fixed(item, items=None): |
| 9 | if items is None: |
| 10 | items = [] |
| 11 | items.append(item) |
| 12 | return items |
| 13 | |
| 14 | print(add_item_fixed("a")) |
| 15 | print(add_item_fixed("b")) |
student@opnf:~$ python3 defaults.py ['a'] ['a', 'b'] ['a'] ['b']
Sample answer
- It prints
['a']then['b'], because each call starts with an empty list.The second call prints['a', 'b']. Default values are created once, when Python defines the function, so every call shares the same list. The fix is to default toNoneand create a new list inside the function.
#2. What's the difference between is and ==?
== asks whether two things have the same value, while is asks whether they're literally the same object in memory. Two lists with the same contents are equal but not identical, and a second name pointing at the same list is both.
| 1 | a = [1, 2, 3] |
| 2 | b = [1, 2, 3] |
| 3 | c = a |
| 4 | |
| 5 | print(a == b) |
| 6 | print(a is b) |
| 7 | print(a is c) |
student@opnf:~$ python3 identity.py True False True
Sample answer
- They're basically the same,
isis just the more readable version.==compares values, andiscompares identity, meaning whether two names point to the exact same object. Two separate lists with the same contents are equal but not identical. I mainly useisfor checking againstNone, which is what PEP 8 recommends.
#3. What's a shallow copy vs a deep copy?
A shallow copy makes a new outer container but keeps pointing at the same objects inside it, while a deep copy copies everything all the way down. The difference only shows up with nested data, so a list of lists is the quickest way to show it.
| 1 | import copy |
| 2 | |
| 3 | original = [[1, 2], [3, 4]] |
| 4 | shallow = copy.copy(original) |
| 5 | deep = copy.deepcopy(original) |
| 6 | |
| 7 | original[0].append(99) |
| 8 | print(shallow) |
| 9 | print(deep) |
student@opnf:~$ python3 copies.py [[1, 2, 99], [3, 4]] [[1, 2], [3, 4]]
Where it breaks
list.copy() and slicing with a[:] are shallow copies too. They're fine for a flat list of numbers, but they'll surprise you the same way with a list of lists.
Sample answer
- A copy is a copy, so changing one never affects the other.A shallow copy makes a new outer object but shares the objects inside it, so changing a nested list shows up in both. A deep copy copies everything recursively, so the two are fully independent.
#4. Why does this function crash with UnboundLocalError?
The variable clearly exists, so the error looks impossible at first. If a function assigns to a variable anywhere inside it, Python treats that name as local to the whole function, so count += 1 tries to read a local count that doesn't exist yet.
| 1 | count = 0 |
| 2 | |
| 3 | def add_one(): |
| 4 | try: |
| 5 | count += 1 |
| 6 | except UnboundLocalError as e: |
| 7 | print(f"UnboundLocalError: {e}") |
| 8 | |
| 9 | def add_one_fixed(): |
| 10 | global count |
| 11 | count += 1 |
| 12 | |
| 13 | add_one() |
| 14 | add_one_fixed() |
| 15 | print(count) |
student@opnf:~$ python3 scope.py UnboundLocalError: cannot access local variable 'count' where it is not associated with a value 1
Sample answer
- Python can't see global variables from inside a function.Because the function assigns to
count, Python treatscountas local for the whole function, socount += 1tries to read a local that has no value yet. I could declare itglobal, but I'd rather pass the value in and return the new one, which keeps the function easy to test.
#5. What is the GIL, and is it going away?
The GIL, or Global Interpreter Lock, is a lock in the standard Python interpreter (CPython) that lets only one thread run Python code at a time. That keeps the interpreter simple and safe, but it means threads can't spread CPU-heavy work across multiple cores, so they mostly help with code that spends its time waiting on networks or disks.
ELI5: explain it simply▾

THE WORDS
- Thread
- One line of work inside a program. A program can run several at once.
- Core
- One worker inside the processor. Modern CPUs have several.
- Lock
- A rule that only lets one thing use something at a time.
THE IDEA
Picture a kitchen with 4 stoves but only 1 chef's hat, and only whoever wears the hat is allowed to cook. Hiring more cooks doesn't make dinner faster, though it still helps while one cook is waiting on a delivery.
The bonus-points part of the answer is that this is changing. Python 3.13 added an experimental build without the GIL, and Python 3.14 made that free-threaded build officially supported, though it's still optional and not the default.
# needs Python 3.13 or newer student@opnf:~$ python3 -c "import sys; print(sys._is_gil_enabled())" True
Sample answer
- The GIL makes Python single-threaded, so threads are useless.The GIL lets only one thread run Python code at a time in CPython, so threads don't speed up CPU-heavy work, but they still help with waiting on things like network calls. For CPU-heavy work I'd look at multiple processes instead. Python 3.14 also made a free-threaded build without the GIL officially supported, though it's optional.
#6. What's a generator, and why use one?
A generator hands out values one at a time, only when asked, instead of building the whole collection in memory first. You make one with yield in a function or with parentheses instead of square brackets, and the payoff shows up fast with big data.
| 1 | import sys |
| 2 | |
| 3 | squares_list = [n * n for n in range(1_000_000)] |
| 4 | squares_gen = (n * n for n in range(1_000_000)) |
| 5 | |
| 6 | print(sys.getsizeof(squares_list)) |
| 7 | print(sys.getsizeof(squares_gen)) |
student@opnf:~$ python3 generators.py 8448728 200
sys.getsizeof reports 8,448,728 bytes for the list against 200 bytes for the generator, even though both describe the same million values.
For your information
These sizes come from Python 3.13 on 64-bit Linux and will differ a little on other versions, but the list will always be far bigger, because a generator's size doesn't grow with the number of values.
Sample answer
- A generator is just a faster list.A generator produces values one at a time, on demand, instead of storing them all in memory first. The trade-off is that you can only loop over it once, so if I need the data twice, I'd use a list.
#7. What is a decorator?
A decorator is a function that wraps another function to add behavior, like timing, logging or permission checks, without changing the original code. The @timer line is just shorthand for slow_add = timer(slow_add), and saying that out loud shows you understand what's actually happening.
| 1 | import time |
| 2 | |
| 3 | def timer(func): |
| 4 | def wrapper(*args, **kwargs): |
| 5 | start = time.perf_counter() |
| 6 | result = func(*args, **kwargs) |
| 7 | print(f"{func.__name__} took {time.perf_counter() - start:.2f}s") |
| 8 | return result |
| 9 | return wrapper |
| 10 | |
| 11 | @timer |
| 12 | def slow_add(a, b): |
| 13 | time.sleep(1) |
| 14 | return a + b |
| 15 | |
| 16 | print(slow_add(2, 3)) |
student@opnf:~$ python3 decorators.py slow_add took 1.00s 5
A common follow-up is what goes wrong with a decorator like this, and the answer is that the wrapper replaces the original function's name and docstring. Adding @functools.wraps(func) to the inner function copies them back, which matters for logging, debugging and documentation tools.
| 1 | import functools |
| 2 | |
| 3 | def plain(func): |
| 4 | def wrapper(*args, **kwargs): |
| 5 | return func(*args, **kwargs) |
| 6 | return wrapper |
| 7 | |
| 8 | def wrapped(func): |
| 9 | @functools.wraps(func) |
| 10 | def wrapper(*args, **kwargs): |
| 11 | return func(*args, **kwargs) |
| 12 | return wrapper |
| 13 | |
| 14 | @plain |
| 15 | def report(): |
| 16 | """Build the weekly report.""" |
| 17 | |
| 18 | @wrapped |
| 19 | def backup(): |
| 20 | """Run the nightly backup.""" |
| 21 | |
| 22 | print(report.__name__, report.__doc__) |
| 23 | print(backup.__name__, backup.__doc__) |
student@opnf:~$ python3 wraps.py wrapper None backup Run the nightly backup.
Sample answer
- It's the @ symbol you put above a function.A decorator is a function that takes a function and returns a wrapped version with extra behavior, like timing or logging.
@timeris shorthand forslow_add = timer(slow_add), and I'd addfunctools.wrapsso the wrapped function keeps its name and docstring.
#8. What do *args and **kwargs do?
*args collects any extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dictionary. That's how the decorator above can wrap any function no matter what arguments it takes.
| 1 | def show(*args, **kwargs): |
| 2 | print(args) |
| 3 | print(kwargs) |
| 4 | |
| 5 | show(1, 2, 3, name="Ada", role="admin") |
student@opnf:~$ python3 args.py (1, 2, 3) {'name': 'Ada', 'role': 'admin'}
A common follow-up flips it around: the same stars also unpack values when you call a function. One star spreads a list into positional arguments, and two stars spread a dictionary into keyword arguments.
| 1 | def show(*args, **kwargs): |
| 2 | print(args) |
| 3 | print(kwargs) |
| 4 | |
| 5 | numbers = [1, 2] |
| 6 | details = {"name": "Ada"} |
| 7 | show(*numbers, **details) |
student@opnf:~$ python3 unpack.py (1, 2) {'name': 'Ada'}
For your information
The names args and kwargs are only a convention. The single and double asterisks are what do the work, so *items and **options behave exactly the same way.
Sample answer
*argsis for numbers and**kwargsis for strings.*argscollects extra positional arguments into a tuple, and**kwargscollects extra keyword arguments into a dictionary. The same stars also unpack a list or dictionary when you call a function.
#9. How does try, except, else and finally work?
Most candidates know try and except, so the follow-up is usually about the other two. The else block runs only when nothing went wrong, and finally runs every single time, which makes it the place for cleanup like closing a file or a connection.
| 1 | def divide(a, b): |
| 2 | try: |
| 3 | result = a / b |
| 4 | except ZeroDivisionError: |
| 5 | print("Can't divide by zero") |
| 6 | return None |
| 7 | else: |
| 8 | print("Division worked") |
| 9 | return result |
| 10 | finally: |
| 11 | print("Cleanup runs every time") |
| 12 | |
| 13 | print(divide(10, 2)) |
| 14 | print(divide(10, 0)) |
student@opnf:~$ python3 errors.py Division worked Cleanup runs every time 5.0 Can't divide by zero Cleanup runs every time None
Sample answer
finallyonly runs when there's an error.tryholds the code that might fail,excepthandles a specific error,elseruns only if nothing failed, andfinallyruns no matter what, so that's where cleanup goes. I catch specific exceptions instead of using a bareexcept, so real bugs still show up.
#10. What's the difference between a list and a tuple?
It's one of the most common basic Python interview questions, which is why it's last here: lists can be changed after they're made and tuples can't. The part most answers skip is why that matters. Dictionary keys must be hashable, and Python's built-in changeable types like lists aren't, so a tuple can be a key only if everything inside it is hashable too.
| 1 | point = (3, 4) |
| 2 | locations = {point: "home"} |
| 3 | print(locations[(3, 4)]) |
| 4 | |
| 5 | try: |
| 6 | point[0] = 10 |
| 7 | except TypeError as e: |
| 8 | print(f"TypeError: {e}") |
student@opnf:~$ python3 tuples.py home TypeError: 'tuple' object does not support item assignment
| 1 | locations = {} |
| 2 | locations[(3, 4)] = "home" |
| 3 | try: |
| 4 | locations[(3, [4, 5])] = "work" |
| 5 | except TypeError as e: |
| 6 | print(f"TypeError: {e}") |
| 7 | print(locations) |
student@opnf:~$ python3 keys.py TypeError: unhashable type: 'list' {(3, 4): 'home'}
Sample answer
- Tuples are just lists you can't change.Lists are mutable and tuples aren't, which makes tuples a good fit for fixed records like coordinates. A tuple made of hashable values is itself hashable, so it can be a dictionary key, and a list can't.
#How to answer Python interview questions out loud
Most Python interview questions aren't really checking whether you memorized a definition. What earns the job is showing how you reason through a problem, how you'd debug it, and that you understand why Python behaves the way it does.
In the room
Do
- Say what you expect the code to print before you run it
- Explain the why, like "defaults are built once", not just the fix
- Ask if you can use the standard library, like collections.Counter
- Test your answer on an edge case, like an empty list
Don't
- Recite a definition with no example behind it
- Go quiet for a long stretch while you think
- Jump into code before restating the question
Coding rounds reward knowing the standard library. Finding repeated values in a list is a classic python coding interview question, and Counter turns it into two lines instead of a nested loop.
| 1 | from collections import Counter |
| 2 | |
| 3 | logins = ["ana", "raj", "ana", "lee", "raj", "ana"] |
| 4 | counts = Counter(logins) |
| 5 | |
| 6 | print([name for name, n in counts.items() if n > 1]) |
| 7 | print(counts.most_common(1)) |
student@opnf:~$ python3 duplicates.py ['ana', 'raj'] [('ana', 3)]

Practice Python hands-on
Write and run Python step by step in a simulated terminal in your browser, from the basics up to the scripts DevOps teams use to automate their work.