Skip to main content
CodingMarble

Interview questions and cheat sheets

Python Interview Questions and Answers With Code

These are sixteen Python questions that interviewers ask again and again, each answered in a few sentences with a short example you can paste into a REPL. Learn the reason behind each answer, because follow-up questions almost always probe the reason rather than the definition.

By CodingMarble · Published · 6 min read

Close-up of a computer keyboard
Photo: Christian Wiediger on Unsplash

How to use this list

Reading answers is the weakest way to prepare. For every question below, open a Python prompt, type the example, change one thing, and predict the output before you press Enter. When your prediction is wrong, that is the exact gap an interviewer would have found. The answers assume Python 3, and the examples are labelled as plain text because the page highlighter has no Python mode.

Practical tip: when you do not know an answer, say what you would type to find out, such as help(), dir(), or a two-line experiment in the REPL. Interviewers often value that habit as much as recall.

Types, mutability and copying

1. What is the difference between mutable and immutable types?

A mutable object can change in place after creation, while an immutable one cannot. Lists, dicts and sets are mutable; ints, floats, strings, tuples and frozensets are immutable. An operation such as adding to a string builds a new object and rebinds the name. This matters because mutable objects are shared by every name that points at them.

2. How do list, tuple, set and dict differ?

A list is an ordered, mutable sequence that allows duplicates. A tuple is an ordered, immutable sequence, often used for fixed records and as dictionary keys. A set holds unique hashable items and gives fast membership tests. A dict maps hashable keys to values and keeps insertion order in modern Python.

3. What is the mutable default argument trap?

Default values are evaluated once, when the function is defined, not on every call. A default list is therefore created a single time and shared by every call that omits the argument. The standard fix is a None default that creates a fresh object inside the function.

Prompt· The trap and the fix
def add_bad(item, bucket=[]):
    bucket.append(item)
    return bucket

print(add_bad(1))   # [1]
print(add_bad(2))   # [1, 2]  <- the same list again

def add_good(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

print(add_good(1))  # [1]
print(add_good(2))  # [2]

4. What is the difference between a shallow and a deep copy?

A shallow copy makes a new outer container but reuses the same inner objects, so changing a nested list shows up in both copies. A deep copy copies everything recursively. Use copy.deepcopy when you need full independence, and expect it to cost more on large structures.

Prompt· Shallow versus deep
import copy

a = [[1], [2]]
b = a.copy()            # shallow
c = copy.deepcopy(a)    # deep

b[0].append(9)
print(a)  # [[1, 9], [2]]  <- changed through b
print(c)  # [[1], [2]]     <- untouched

5. What is the difference between is and ==?

The == operator asks whether two values are equal, by calling __eq__. The is operator asks whether two names refer to the very same object in memory. Use == for values and reserve is for singletons such as None. Small integers and some strings may be reused by the interpreter, so is can seem to work on them by accident; never rely on that.

Prompt· Equal but not identical
x = [1, 2]
y = [1, 2]
print(x == y)   # True
print(x is y)   # False
print(x is x)   # True

Functions, generators and decorators

6. What do *args and **kwargs do?

In a function definition, *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. At a call site the same stars unpack a sequence or a mapping into arguments. They let a wrapper forward whatever it receives without knowing the signature, which is why decorators use them.

7. What is a list comprehension, and when should you avoid one?

A list comprehension builds a list from an iterable in one expression, optionally filtered, such as [n * n for n in nums if n % 2 == 0]. It is usually clearer and a little faster than an append loop. Avoid it when the logic needs several statements or nested conditions that make it hard to read, and use a generator expression when you only need to iterate once and do not want the whole list in memory.

8. What are generators and what does yield do?

A function containing yield returns a generator, an iterator that runs the function body lazily. Each call to next() resumes execution after the previous yield, keeping local state. Values are produced on demand, so a generator can walk a huge file or an endless sequence in constant memory. It can be consumed only once.

Prompt· A generator that counts down
def countdown(n):
    while n > 0:
        yield n
        n -= 1

gen = countdown(3)
print(next(gen))        # 3
print(list(gen))        # [2, 1]  (3 was already consumed)
print(list(countdown(3)))  # [3, 2, 1]

9. How do iterators differ from iterables?

An iterable is anything you can loop over because it implements __iter__, which returns an iterator. An iterator implements __next__, returns the next value, and raises StopIteration when finished. A list is iterable but not an iterator; calling iter() on it gives one. A for loop calls iter() once and then next() repeatedly.

10. What is a decorator?

A decorator is a callable that takes a function and returns a replacement, applied with the @ syntax. It adds behaviour such as timing, caching or access checks without editing the original function. Use functools.wraps inside it so the wrapped function keeps its name and docstring, which matters for debugging and documentation tools.

Prompt· A small logging decorator
import functools

def logged(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("calling", func.__name__)
        return func(*args, **kwargs)
    return wrapper

@logged
def add(a, b):
    return a + b

print(add(2, 3))   # prints "calling add" then 5

Objects, context managers and exceptions

11. What is a context manager?

A context manager ensures setup and cleanup around a block using the with statement. It implements __enter__ and __exit__, or is written as a generator with contextlib.contextmanager. Files, locks and database transactions use it so that cleanup runs even when an exception is raised. The cleanup step is the point, not the syntax.

Prompt· A timer written with contextlib
from contextlib import contextmanager
import time

@contextmanager
def timer(label):
    start = time.perf_counter()
    try:
        yield
    finally:
        print(label, "took", round(time.perf_counter() - start, 4), "s")

with timer("sum"):
    total = sum(range(1_000_000))

12. How does exception handling work?

Code in try runs first; a matching except block handles a raised exception; else runs only if nothing was raised; finally always runs. Catch the narrowest exception you can handle, because a bare except hides bugs and even swallows KeyboardInterrupt. Use raise inside a handler to re-raise, and raise NewError from err to keep the original cause visible in the traceback.

13. What are dunder methods?

Dunder, or magic, methods have double underscores on both sides and let your class plug into the language: __init__ sets up an object, __repr__ gives an unambiguous string for debugging, __eq__ defines equality, __len__ powers len(), and __iter__ makes it iterable. Python calls them for you; you rarely call them directly. If you define __eq__ without __hash__, instances become unhashable.

Prompt· A tiny value class
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __eq__(self, other):
        return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)

print(Point(1, 2))                # Point(1, 2)
print(Point(1, 2) == Point(1, 2)) # True

The GIL, environments and type hints

14. What is the GIL, in plain terms?

The Global Interpreter Lock is a lock in the standard CPython interpreter that lets only one thread execute Python bytecode at a time. As a result, threads do not speed up CPU-heavy pure-Python work, though they still help with I/O waits such as network calls, because the lock is released while waiting. For CPU-bound work, use multiprocessing or a native library. Interpreter builds and versions are evolving here, so check the current documentation before answering for a specific release.

15. What is a virtual environment and why use one?

A virtual environment is an isolated directory holding its own Python interpreter link and installed packages, so each project keeps its own dependency versions. Without it, installing for one project can break another. Create it with python -m venv .venv, activate it, and record dependencies in requirements.txt or a pyproject.toml file so teammates can reproduce the setup.

Shell· Create, activate and freeze an environment (Linux and macOS)
python3 -m venv .venv
source .venv/bin/activate
pip install requests
pip freeze > requirements.txt
deactivate

16. What are type hints, and does Python enforce them?

Type hints annotate parameters and return values, such as def total(prices: list[float]) -> float. The interpreter does not enforce them at runtime. They serve readers, editors and static checkers such as mypy, which catch mismatches before the code runs. Adopt them gradually, starting with public functions.

Prompt· Hints on a function and an optional value
def total(prices: list[float], tax: float | None = None) -> float:
    base = sum(prices)
    return base if tax is None else base * (1 + tax)

print(total([10.0, 20.0]))        # 30.0
print(total([10.0, 20.0], 0.5))   # 45.0

Answering well under pressure

A strong answer has three parts: a one-sentence definition, the reason it exists, and a short example or a trade-off. For the mutable default trap, say it is evaluated once at definition time, show the shared list, then show the None fix. That structure also keeps you from rambling.

Expect follow-ups that combine topics. A generator is an iterator, a context manager can be a generator, and a decorator uses *args and **kwargs. If you understand how Python names refer to objects, most of this list collapses into that single idea. Practise explaining it aloud, and run every example in your own interpreter to confirm the output rather than trusting any page, including this one.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.