Python Interview Cheat Sheet
Core syntax, fundamentals, and interview Q&A for mid-to-senior backend engineers
Review syntax blocks first, then practice the interview questions aloud.
How to use this PDF
Focus on writing small examples without looking up syntax.
1) core syntax 2) common pitfalls 3) explain behavior 4) solve small coding
Best prep order
problems cleanly
Variables, types, and truthiness
Know: int, float, bool, str, list, tuple, dict, set, None.
Truthiness: False, None, 0, 0.0, '', [], {}, set() are falsy; most other objects are truthy.
x = 10
name = "sam"
items = []
if not items:
print("empty")
Interview questions
Q: What is truthy and falsy in Python?
A: Empty collections, 0-like values, False, and None are falsy. Most other objects are truthy.
Q: What is the difference between == and is?
A: == compares value. is compares identity, meaning whether both references point to the same object.
Conditionals
Know: if / elif / else, ternary expressions, short-circuit behavior of and/or.
age = 20
status = "adult" if age >= 18 else "minor"
if age > 60:
group = "senior"
elif age >= 18:
group = "adult"
else:
group = "minor"
Interview questions
Q: What is short-circuiting?
A: Python stops evaluating as soon as the result is known. In a and b, if a is falsy, b is not evaluated. In a or b, if a is truthy,
b is not evaluated.
Loops
Know: for, while, break, continue, enumerate, zip, and loop else.
Loop else: runs only if the loop finishes without break.
for i in range(3):
print(i)
for x in [1, 3, 5]:
if x == 4:
break
else:
Python interview cheat sheet Page 1
print("not found")
Interview questions
Q: When does else on a loop run?
A: It runs when the loop completes normally, without hitting break.
Q: Why use enumerate instead of manual index handling?
A: It is clearer, less error-prone, and directly gives index plus value.
Functions and arguments
Know: positional args, keyword args, default args, *args, **kwargs, keyword-only args.
def greet(name, title="Engineer"):
return f"Hi {name}, {title}"
def add_all(*nums):
return sum(nums)
def config(**kwargs):
return kwargs
def f(a, *, verbose=False):
return a
Interview questions
Q: Why are mutable default arguments dangerous?
A: They are evaluated once at function definition time, so the same object is reused across calls.
Q: What are *args and **kwargs?
A: *args collects extra positional arguments as a tuple. **kwargs collects extra keyword arguments as a dict.
Comprehensions
Know: list, set, dict comprehensions and simple conditional filtering.
squares = [x*x for x in range(5)]
evens = {x for x in range(10) if x % 2 == 0}
mapping = {x: x*x for x in range(4)}
Interview questions
Q: When should you avoid comprehensions?
A: When the logic becomes too nested or hard to read. Readability is more important than writing one line.
Slicing
Know: start:stop:step, negative indexes, reversing with [::-1].
nums = [0, 1, 2, 3, 4, 5]
nums[1:4] # [1, 2, 3]
nums[::-1] # reversed
nums[::2] # every second item
Interview questions
Q: Does slicing create a copy?
A: For built-in sequence types like list and str, slicing returns a new object containing the selected range.
f-strings
Know: readable interpolation, expressions inside braces, format specifiers.
Python interview cheat sheet Page 2
name = "Sam"
score = 93.456
msg = f"{name} scored {score:.2f}"
Interview questions
Q: Why are f-strings preferred?
A: They are readable, concise, and support inline expressions and formatting.
Unpacking
Know: tuple/list unpacking, starred unpacking, merging iterables and dicts.
a, b = (1, 2)
first, *rest = [10, 20, 30, 40]
combined = [*range(3), 99]
merged = {**{'a': 1}, **{'b': 2}}
Interview questions
Q: What does *rest do?
A: It gathers the remaining positional items into a list during unpacking.
Context managers
Know: with, automatic cleanup, file handling, custom __enter__ / __exit__.
with open("[Link]") as f:
data = [Link]()
Interview questions
Q: Why use with?
A: It guarantees cleanup, such as closing files or releasing resources, even if an exception occurs.
Q: What protocol powers a context manager?
A: Objects implementing __enter__ and __exit__.
Exceptions
Know: try, except, else, finally, raise, custom exceptions.
try:
value = int("42")
except ValueError:
print("bad input")
else:
print("parsed")
finally:
print("done")
Interview questions
Q: When does else in try/except run?
A: It runs only if no exception was raised in the try block.
Q: What should you avoid in exception handling?
A: Catching overly broad exceptions unless you re-raise or handle them intentionally.
Imports and modules
Know: import x, from x import y, aliases, package layout, __name__ == '__main__'.
import math
from collections import Counter
Python interview cheat sheet Page 3
import json as js
if __name__ == "__main__":
print("run as script")
Interview questions
Q: Why can from module import * be a problem?
A: It pollutes the namespace and makes code harder to read and maintain.
Classes, inheritance, super()
Know: instance attributes, class attributes, __init__, inheritance, overriding, super().
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "woof"
class Base:
def __init__(self, name):
[Link] = name
class Child(Base):
def __init__(self, name, age):
super().__init__(name)
[Link] = age
Interview questions
Q: What does super() do?
A: It gives access to methods of the parent class according to Python's method resolution order.
Q: Class attribute vs instance attribute?
A: Class attributes are shared across instances unless overridden. Instance attributes belong to each object.
Iterators and generators
Know: iterable vs iterator, iter(), next(), yield, generator expressions, lazy evaluation.
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for n in count_up_to(3):
print(n)
Interview questions
Q: Iterable vs iterator?
A: An iterable can be looped over. An iterator is the object that keeps state and returns items one by one with next().
Q: Why use generators?
A: They are memory-efficient and useful for streaming or large datasets because they produce items lazily.
Decorators
Know: higher-order functions, wrappers, @decorator syntax, [Link].
Python interview cheat sheet Page 4
from functools import wraps
def log_calls(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
print("calling", fn.__name__)
return fn(*args, **kwargs)
return wrapper
@log_calls
def add(a, b):
return a + b
Interview questions
Q: Why use [Link]?
A: It preserves metadata like the original function name and docstring.
Q: Common decorator use cases?
A: Logging, authorization, retries, timing, caching, and validation.
lambda, map, filter, sorted(key=...)
Know: use lambda sparingly, prefer readability, key functions are common in interviews.
nums = [3, 1, 2]
sorted_nums = sorted(nums)
users = [{"name": "A", "age": 30}, {"name": "B", "age": 25}]
users_by_age = sorted(users, key=lambda u: u["age"])
evens = list(filter(lambda x: x % 2 == 0, nums))
doubled = list(map(lambda x: x * 2, nums))
Interview questions
Q: When should you avoid lambda?
A: When a named function or comprehension is clearer.
Q: What is sorted(key=...)?
A: The key function transforms each item for comparison, without changing the original item itself.
Python interview cheat sheet Page 5
Core Python pitfalls to memorize
Mutable default argument Use None and create a new object inside the function.
Loop variables captured by inner functions are looked up when the
Late binding in closures
function runs, not when it is created.
Use is for identity checks, especially with None; use == for value
is vs ==
comparison.
A shallow copy copies the container only. Nested mutable objects are
Shallow vs deep copy
still shared.
Modifying a list while Can skip items or behave unpredictably. Iterate over a copy or build a
iterating new list.
Using broad except Can hide real bugs and make debugging harder.
Rapid-fire interview prompts
• Explain Python mutability with examples.
• Explain the difference between list, tuple, set, and dict with use cases.
• Write a function using *args and **kwargs.
• Explain generator vs list.
• Explain how decorators work.
• Show how loop else works.
• Explain super() and method overriding.
• Explain when with is preferred over manual cleanup.
• Explain try / except / else / finally with one real example.
• Sort a list of dicts by multiple fields using key.
Short coding drills
Group words by first letter
words = ["apple", "ant", "bat"]
result = {}
for w in words:
[Link](w[0], []).append(w)
Count frequencies
from collections import Counter
counts = Counter(["a", "b", "a"])
Safe file read
def read_text(path):
try:
with open(path) as f:
return [Link]()
except FileNotFoundError:
return ""
Sort users by age then name
users = [{"name": "Sam", "age": 30}, {"name": "Ana", "age": 30}]
users = sorted(users, key=lambda u: (u["age"], u["name"]))
Python interview cheat sheet Page 6