This page collects Python interview questions that come up again and again, with answers you can explain and back up with a few lines of code. Interviewers usually care less about a memorised definition than about whether you can show why something behaves the way it does, so each answer includes a small demonstration.
first = ["rehearsal"]
second = first
second.append("performance")
print(first) # ['rehearsal', 'performance']: one list, two namesThe questions are grouped into how to answer, core language behaviour, approaching coding problems, and discussing trade-offs. The examples use a theatre scheduling rehearsals and performances. Pair this page with the coding challenges and complexity lessons for practice.
Reasoned explanations
A strong answer has three parts: a one-sentence definition, a tiny example, and a consequence that matters in real code.
Q: What is the difference between a list and a tuple? A list is mutable; a tuple is immutable. t = (1, 2); t[0] = 5 raises TypeError. Consequence: tuples can be dictionary keys and are safe to share, so they suit fixed records such as coordinates.
Q: What does "mutable" mean, and why does it matter? A mutable object can be changed in place. Two names can refer to one mutable object, so a change through one name shows through the other, as in the example above. Consequence: copy (list.copy(), copy.deepcopy()) before modifying data you were given.
Q: What are *args and **kwargs? *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary. Consequence: wrappers such as decorators can accept and forward any arguments.
Practise saying each answer out loud in under a minute, then typing the demonstration from memory.
Language semantics
Q: What is the difference between is and ==? == compares values; is compares identity (the same object). [1] == [1] is True, [1] is [1] is False. Use is only for None and other singletons. Small integers and short strings may appear identical because CPython caches them, but that's an implementation detail, not a rule to rely on.
Q: Why is a mutable default argument a bug? Defaults are evaluated once, when the function is defined. def add(item, items=[]) shares one list between calls. Use items=None and create the list inside.
Q: What is a generator? A function containing yield. It produces values lazily, one per next() call, keeping its local state between them, so it can process large or endless data in constant memory. Generators can only be iterated once.
Q: What is a decorator? A function that takes a function and returns a new one, adding behaviour. @timer above def f means f = timer(f). Use functools.wraps to keep the original name and docstring.
Q: What is the GIL? In CPython, the Global Interpreter Lock lets only one thread execute Python bytecode at a time. Threads still help with I/O-bound work; CPU-bound work uses multiprocessing or native extensions. Python 3.13 added an experimental free-threaded build without the GIL.
Problem discussion
For coding questions, the process matters as much as the final answer. Before writing code:
- Restate the problem and confirm the inputs and outputs. "Given rehearsal slots as (start, end) pairs, return whether any overlap?"
- Ask about constraints: can the list be empty? Are times integers? Do slots that touch at 18:00 count as overlapping? How large can the input be?
- Work through a small example by hand, including an edge case.
- State a simple approach first, then improve it if needed.
def has_overlap(slots):
ordered = sorted(slots)
return any(prev_end > start for (_, prev_end), (start, _) in zip(ordered, ordered[1:]))
print(has_overlap([(14, 16), (9, 11), (15, 17)])) # True
print(has_overlap([(9, 11), (11, 13)])) # False: touching isn't overlappingTalk while you code, test with the examples you prepared, and mention what you would add with more time, such as input validation. A correct solution to a problem the interviewer didn't ask is not a correct answer, which is why clarifying questions come first.
Tradeoffs
Interviewers often ask "can you do better?" or "what are the trade-offs?". Discuss them in terms of the actual task:
- Time complexity: sorting the slots costs O(n log n) and the scan O(n). Comparing every pair would be O(n²), fine for 20 rehearsals, not for a million bookings.
- Data structures: checking membership in a list is O(n); in a set or dictionary it's O(1) on average. Repeated lookups by performer name call for a dictionary.
- Memory: a generator avoids building a large list; sorting a copy uses extra memory but leaves the caller's data untouched.
- Readability and testing: the clear O(n log n) version is usually better than a clever but fragile one.
performers = ["Ana", "Ben", "Cara"] * 1000
lookup = set(performers)
print("Cara" in lookup) # average O(1) instead of scanning the listJustify optimisations with the expected workload. "This runs once a night over 200 rows" and "this runs on every request over 10 million rows" deserve different answers.
Independent practice and a worked check
Task: answer questions on mutable defaults, generators, None, equality, decorators and complexity with original scheduling examples. One way to check yourself is to write each answer as a tested function:
def next_free(booked, schedule=None): # no mutable default
schedule = schedule if schedule is not None else ["Mon", "Tue", "Wed"]
return next((d for d in schedule if d not in booked), None)
booked = {"Mon"} # set: O(1) membership
print(next_free(booked)) # Tue
print(next_free({"Mon", "Tue", "Wed"})) # None: no free day
print(next_free(booked) == "Tue") # value equalityThe generator inside next() stops at the first match, None signals "nothing found", and the set keeps lookups fast. For the worked check: editing second also changed first because both names reference the same list.
Reference and next practice
The official Python FAQ answers many classic questions, including mutable defaults and closures. Continue with coding challenges and practice problems. Practise with the Python exercises and Python quiz.
Interview Questions and Answers Summary
- Reasoned explanations: A strong answer states a concept and demonstrates it with a small counterexample or trace.
- Language semantics: Common questions distinguish equality, identity, iteration and mutable defaults.
- Problem discussion: Clarify inputs, constraints and expected results before coding.
- Tradeoffs: Discuss complexity, error handling, tests and readability in relation to the given task.
Interview Questions and Answers Examples
Each example shows the code, the output it produces and what each part does.
Interview Questions and Answers in a small program
A classic question: "what does this print, and why?"
first = ["rehearsal"]
second = first
second.append("performance")
print(first)
print(first is second)['rehearsal', 'performance']
TrueLine-by-line explanation
- Line 2
second = firstbinds a second name to the same list; nothing is copied. - Line 3Appending through
secondchanges that one list. - Lines 4 to 5
firstshows the new item, andisconfirms both names refer to the same object.
Five quick demonstrations
import functools
# 1. Mutable default argument
def add_slot(slot, slots=[]):
slots.append(slot)
return slots
add_slot("Mon")
print(add_slot("Tue"))
# 2. Generators are single-use
squares = (n * n for n in range(3))
print(list(squares), list(squares))
# 3. A decorator that preserves metadata
def shout(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs).upper()
return wrapper
@shout
def greet(name):
"""Greet a performer."""
return f"break a leg, {name}"
print(greet("Ana"), greet.__name__)
# 4. == versus is
a, b = [1, 2], [1, 2]
print(a == b, a is b)
# 5. Late binding in closures
callbacks = [lambda: i for i in range(3)]
print([f() for f in callbacks])['Mon', 'Tue']
[0, 1, 4] []
BREAK A LEG, ANA greet
True False
[2, 2, 2]Line-by-line explanation
- Lines 4 to 8The default list is shared, so the second call returns both slots.
- Lines 11 to 12The second
list()gets nothing because the generator is exhausted. - Lines 32 to 33Each lambda looks up
iwhen called, after the loop has finished, so all return 2. Fix withlambda i=i: i.
Common Interview Questions and Answers Mistakes
Answering with a definition and no demonstration
Q: What is a generator?
A: A generator is an iterator that uses yield.Q: What is a generator?
A: A function with yield that produces values lazily. For example,
(line for line in open("log.txt") if "ERROR" in line) filters a
10 GB log using constant memory, but can only be looped over once.Coding before clarifying the problem
Interviewer: "Find overlapping rehearsals."
Candidate immediately writes a nested loop comparing every pair.Candidate: "Do slots that touch at the boundary count as overlapping?
Can the input be empty? Roughly how many slots?" Then sorts and scans.Interview Questions and Answers in Real Projects
Preparing for Python interviews
Junior roles tend to focus on core language behaviour (data types, mutability, functions, classes, exceptions) and simple coding problems with lists, strings and dictionaries. Mid-level roles add generators, decorators, context managers, testing, complexity and design discussions. Data roles add pandas and SQL; web roles add HTTP, APIs and databases.
Prepare by explaining concepts aloud, solving timed problems on paper or a plain editor, and reviewing your own past projects so you can discuss decisions you made. Many companies now use realistic tasks, such as fixing a bug in a small codebase, so practical skills from the debugging and testing lessons are directly relevant.
Interview Questions and Answers FAQ
What Python topics are asked most in interviews?
Data types and mutability, lists versus tuples versus sets versus dictionaries, functions and arguments, is versus ==, exceptions, classes and inheritance, comprehensions, generators, decorators, and time complexity. Coding rounds usually use strings, lists, dictionaries and sorting.
How should I prepare for a Python coding interview?
Solve problems regularly in a plain editor, say your reasoning aloud, and practise clarifying questions and edge cases. Review complexity for common operations, and be ready to discuss projects you've built, including mistakes and what you'd change.
What is the difference between a shallow copy and a deep copy?
A shallow copy creates a new outer object that still refers to the same inner objects; a deep copy duplicates the inner objects too. Show it with a list of lists: changing an inner list affects a shallow copy but not a deep one.
Is Python pass-by-value or pass-by-reference?
Neither, strictly: Python passes references to objects ("pass by object reference"). A function can mutate a mutable argument, and the caller sees the change, but rebinding the parameter to a new object inside the function doesn't affect the caller's variable.
What is the difference between a process and a thread in Python?
Threads share one process's memory and, in standard CPython, take turns running Python code because of the GIL, so they suit I/O-bound work. Processes have separate memory and run truly in parallel, so they suit CPU-bound work, at the cost of more overhead for sharing data.
Interview Questions and Answers Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Why did editing second also change first?
Which review concern is valid for interview questions and answers?
Interview Questions and Answers Quiz
2 questions to check what you learned.
Why did editing second also change first?
- Every list is globally shared
- Both names reference the same list
- Python ignores the distinction
Which statement correctly describes problem discussion?
- Clarify inputs, constraints and expected results before coding.
- Only the example output matters, not the rule
- Every operation has the same behavior