Guides / DevOps / Python interview questions: 10 with answers
DevOps · Explainer

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.

opnF.shNov 11, 202611 min readpython interview questionspythoninterview prep
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 Counter and functools.wraps answer common follow-ups in a line or two.
New to this?Ping explains the hardest part in plain words.

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:

#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.

defaults.pyPYTHON
1def add_item(item, items=[]):
2 items.append(item)
3 return items
4
5print(add_item("a"))
6print(add_item("b"))
7
8def add_item_fixed(item, items=None):
9 if items is None:
10 items = []
11 items.append(item)
12 return items
13
14print(add_item_fixed("a"))
15print(add_item_fixed("b"))
run defaults.py
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 to None and 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.

identity.pyPYTHON
1a = [1, 2, 3]
2b = [1, 2, 3]
3c = a
4
5print(a == b)
6print(a is b)
7print(a is c)
run identity.py
student@opnf:~$ python3 identity.py
True
False
True

Sample answer

  • They're basically the same, is is just the more readable version.
    == compares values, and is compares 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 use is for checking against None, 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.

copies.pyPYTHON
1import copy
2
3original = [[1, 2], [3, 4]]
4shallow = copy.copy(original)
5deep = copy.deepcopy(original)
6
7original[0].append(99)
8print(shallow)
9print(deep)
run copies.py
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.

scope.pyPYTHON
1count = 0
2
3def add_one():
4 try:
5 count += 1
6 except UnboundLocalError as e:
7 print(f"UnboundLocalError: {e}")
8
9def add_one_fixed():
10 global count
11 count += 1
12
13add_one()
14add_one_fixed()
15print(count)
run scope.py
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 treats count as local for the whole function, so count += 1 tries to read a local that has no value yet. I could declare it global, 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
Ping explainsNo experience needed.
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.

check for the GIL
# 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.

generators.pyPYTHON
1import sys
2
3squares_list = [n * n for n in range(1_000_000)]
4squares_gen = (n * n for n in range(1_000_000))
5
6print(sys.getsizeof(squares_list))
7print(sys.getsizeof(squares_gen))
run generators.py
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.

i
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.

decorators.pyPYTHON
1import time
2
3def 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
12def slow_add(a, b):
13 time.sleep(1)
14 return a + b
15
16print(slow_add(2, 3))
run decorators.py
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.

wraps.pyPYTHON
1import functools
2
3def plain(func):
4 def wrapper(*args, **kwargs):
5 return func(*args, **kwargs)
6 return wrapper
7
8def wrapped(func):
9 @functools.wraps(func)
10 def wrapper(*args, **kwargs):
11 return func(*args, **kwargs)
12 return wrapper
13
14@plain
15def report():
16 """Build the weekly report."""
17
18@wrapped
19def backup():
20 """Run the nightly backup."""
21
22print(report.__name__, report.__doc__)
23print(backup.__name__, backup.__doc__)
run wraps.py
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. @timer is shorthand for slow_add = timer(slow_add), and I'd add functools.wraps so 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.

args.pyPYTHON
1def show(*args, **kwargs):
2 print(args)
3 print(kwargs)
4
5show(1, 2, 3, name="Ada", role="admin")
run args.py
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.

unpack.pyPYTHON
1def show(*args, **kwargs):
2 print(args)
3 print(kwargs)
4
5numbers = [1, 2]
6details = {"name": "Ada"}
7show(*numbers, **details)
run unpack.py
student@opnf:~$ python3 unpack.py
(1, 2)
{'name': 'Ada'}
i
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

  • *args is for numbers and **kwargs is for strings.
    *args collects extra positional arguments into a tuple, and **kwargs collects 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.

errors.pyPYTHON
1def 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
13print(divide(10, 2))
14print(divide(10, 0))
run errors.py
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

  • finally only runs when there's an error.
    try holds the code that might fail, except handles a specific error, else runs only if nothing failed, and finally runs no matter what, so that's where cleanup goes. I catch specific exceptions instead of using a bare except, 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.

tuples.pyPYTHON
1point = (3, 4)
2locations = {point: "home"}
3print(locations[(3, 4)])
4
5try:
6 point[0] = 10
7except TypeError as e:
8 print(f"TypeError: {e}")
run tuples.py
student@opnf:~$ python3 tuples.py
home
TypeError: 'tuple' object does not support item assignment
keys.pyPYTHON
1locations = {}
2locations[(3, 4)] = "home"
3try:
4 locations[(3, [4, 5])] = "work"
5except TypeError as e:
6 print(f"TypeError: {e}")
7print(locations)
run keys.py
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.

duplicates.pyPYTHON
1from collections import Counter
2
3logins = ["ana", "raj", "ana", "lee", "raj", "ana"]
4counts = Counter(logins)
5
6print([name for name, n in counts.items() if n > 1])
7print(counts.most_common(1))
run duplicates.py
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.

Open ›
How should I prepare for a Python interview?
Practice explaining, not just recognizing. Pick 5 to 10 classic questions, type each example from memory, then change one line and explain what breaks, since follow-up questions usually poke at exactly that.
What are the basic Python questions asked in an interview?
Common ones include lists vs tuples, is vs ==, mutable default arguments, copying, error handling and what *args and **kwargs do. Each is short enough to answer with a 5-line example, so expect to be asked to write or explain one on the spot.
Is Python good for coding interviews?
It's a popular choice, because its short syntax and built-in tools like Counter and sorted let you spend interview time on the problem instead of boilerplate. Still, confirm which languages a company allows before you walk in.
Do I need to know pandas or NumPy for a Python interview?
Mostly for data and AI roles. General Python developer interviews tend to focus on the core language, while data analyst and machine learning interviews usually add libraries like pandas and NumPy on top.
opnF.sh
Hands-on guides from the team that builds the labs you practice in.