Python interview questions with model answers
32 questions written alongside the free Python course, each with the answer an interviewer is listening for. 30 are below, spread from first principles to advanced; the rest are in the course.
What Python interviews test
Python interviews probe the data model and the standard library: mutability and default arguments, how lists, dicts and sets behave, comprehensions and generators, decorators, exceptions and context managers, and where the GIL does and doesn't limit concurrency.
1. Is Python compiled or interpreted?
Interpreted — CPython compiles to bytecode and then runs it on a virtual machine, so there is a compilation step, but you never invoke it and there is no separate build artifact. Practically it behaves as interpreted.
From the lesson What Python Is and Why It Won
2. What does print("5" + "3") show?
53. Both are strings, so + concatenates rather than adds. print(5 + 3) would show 8.
From the lesson Your First Program: print()
3. Why does Python use indentation instead of braces?
Because the visual structure and the actual structure can never disagree. In brace languages, badly indented code can mislead a reader about what the program does; in Python that is impossible.
From the lesson Comments, Statements and Indentation
4. How do you read a Python traceback?
Bottom up. The final line gives the exception type and message, which is the actual problem. The lines above are the call chain, most recent last, showing how execution reached that point.
From the lesson Reading Errors and Tracebacks
5. What does a, b = b, a actually do?
Python builds a tuple of the right-hand values first, then unpacks it into the targets. Because the right side is fully evaluated before any assignment happens, the swap works without a temporary variable.
From the lesson Variables and Assignment
6. Explain the difference between == and is.
== compares values; is compares identity. Two distinct lists with equal contents are == but not is. In practice use is only for None, True and False, because small ints and short strings are cached and identity comparisons on them give misleading results.
From the lesson Mutability, Identity and References
7. What is the difference between "" and None?
An empty string is a string that happens to have no characters — a real value. None is the absence of any value. A blank form field is ""; a field that was never asked about is None.
From the lesson Numbers, Strings, Booleans and None
8. Why does 0.1 + 0.2 != 0.3, and how do you compare floats?
Floats are binary fractions and 0.1 has no exact binary form, so a tiny error appears. Compare with math.isclose() or an explicit tolerance, and avoid floats for money entirely.
From the lesson Numeric Types and Their Limits
9. Why does input() need converting, and what can go wrong?
It always returns a string, so arithmetic raises TypeError. Converting with int() can raise ValueError when the text is not numeric, so real programs check first with isdigit() or wrap the conversion in try/except.
From the lesson input() and Validating User Input
10. How do you show a number to two decimal places?
f"{value:.2f}". The colon starts the format spec, .2 is the precision and f means fixed-point. Note it rounds for display only — the underlying value is unchanged.
From the lesson f-strings and Formatting
11. Why is 0.1 + 0.2 != 0.3?
Floats are stored in binary, and 0.1 has no exact binary representation, so a tiny error is introduced and shows up in the sum. Compare with a tolerance, or use decimal.Decimal for exact decimal arithmetic.
From the lesson Arithmetic and Precision
12. What does "" or "guest" return, and why?
"guest". or returns the first truthy operand rather than a boolean, and an empty string is falsy. It is the standard idiom for supplying a default.
From the lesson Comparison, Logic and Precedence
13. How would you check whether an integer is a power of two?
n > 0 and n & (n - 1) == 0. A power of two has exactly one bit set; subtracting one flips that bit off and sets every bit below it, so the AND is zero. The n > 0 guard matters because 0 and negative numbers would otherwise slip through.
From the lesson Bitwise Operators
14. What is the difference between elif and a second if?
elif is only tested when everything above it was false, and only one branch in the chain can run. Separate ifs are all tested independently, so several can fire.
From the lesson if, elif and else
15. Which values are falsy in Python?
False, None, zero of any numeric type, and every empty container — "", [], (), {}, set(). Everything else is truthy, which catches people out with strings like "0" and "False".
From the lesson Truthiness and Conditional Expressions
16. How do you loop with both index and value?
enumerate(seq), which yields (index, item) pairs. It takes a start argument if you want 1-based numbering. range(len(seq)) works but is not idiomatic.
From the lesson for Loops and range()
17. What does else after a for loop mean?
It runs only if the loop completed without breaking. The classic use is a search: break when found, and the else handles the not-found case without needing a flag variable.
From the lesson while Loops, break and continue
18. What happens if you remove items from a list while looping over it?
The loop skips elements, because indexes shift left while the internal counter moves right. It produces a wrong result silently. Build a new list with a comprehension, or iterate over a copy.
From the lesson Loop Tracing, Sentinels and Off-by-One
19. Why does slicing exclude the stop index?
So that s[:n] + s[n:] always rebuilds the original, and len(s[a:b]) is exactly b - a. Both properties would fail if stop were inclusive.
From the lesson Indexing and Slicing
20. Why is join called on the separator?
Because join works with any iterable of strings, so putting it on str keeps one implementation instead of adding a join method to list, tuple, set and every other container.
From the lesson String Methods That Do the Work
21. What is the difference between sort() and sorted()?
sort() is a list method that mutates in place and returns None. sorted() is a built-in that works on any iterable and returns a new list. Use sorted when you need the original preserved or when the input is not a list.
From the lesson Lists
22. When should you not use a comprehension?
When it stops being readable on one line — multiple nested loops, several conditions, or side effects. A comprehension is for building a collection; if the loop body is doing work rather than producing values, write a normal loop.
From the lesson List Comprehensions
23. When would you use a tuple instead of a list?
When the group has a fixed shape and each position carries meaning — a coordinate, a database row, a multi-value return. Immutability also makes tuples hashable, so they work as dict keys and set members, which lists cannot.
From the lesson Tuples, Packing and Unpacking
24. When would you choose a namedtuple over a dataclass?
When the value really is a fixed, immutable row and you want tuple behaviour: equality with plain tuples, hashability, unpacking, and the smaller memory footprint. A dataclass is the better answer as soon as you want defaults, methods, mutability, or more than a handful of fields — readability wins over tuple compatibility.
From the lesson Named Tuples and the Sequence Protocol
25. Why is x in a_set faster than x in a_list?
A set is a hash table: it computes where the value would live and looks there, roughly constant time. A list has no such structure and must compare each element in turn, linear in the length.
From the lesson Sets, Frozensets and Fast Membership
26. How do you count occurrences of items?
counts[item] = counts.get(item, 0) + 1 in a loop, or collections.Counter(items) which does it in one call. The get() default is what avoids the KeyError on first sight of a key.
From the lesson Dictionaries
27. What is the difference between a shallow and a deep copy?
A shallow copy creates a new outer container whose elements still point at the same inner objects; a deep copy recreates the structure recursively. For a flat list of immutables they are equivalent; for nested mutable data only deepcopy prevents shared-state bugs.
From the lesson Copying, Deep Copies and Shared State
28. What is the difference between return and print?
print writes to the console and returns None; return sends a value back to the caller. Only returned values can be stored, combined or asserted on in a test, which is why library code returns and only the outermost layer prints.
From the lesson Defining and Calling Functions
29. Why is a mutable default argument dangerous?
Defaults are evaluated once when the function is defined, so every call without that argument shares the same object. A list default accumulates across calls. The fix is to default to None and build the container inside the function.
From the lesson Arguments: Defaults, Keywords, *args and **kwargs
30. What is a closure?
A nested function that captures and remembers variables from the enclosing scope, and keeps them alive after the outer function has returned. It is what lets a decorator wrap a function while still referring to it.
From the lesson Scope, Closures and Lambdas
Learn it, then drill it
The Python course teaches every one of these in context, with runnable examples. For drilling, the practice bank has 2,620 multiple-choice Python questions with explanations.