Python Roadmap
Python is a readable, general-purpose language used for web back ends, automation, data analysis, machine learning, testing and tooling. It is also one of the most popular languages for coding interviews, because solutions are short and the built-in collections cover most of what an algorithm needs. Back-end, data, machine learning and DevOps roles all expect it.
This roadmap starts with syntax and built-in types and moves through functions, object-oriented design, iterators and decorators, data structures and algorithms, type hints, packaging, testing, concurrency and the main frameworks. Topics follow the order in which ideas build on each other. Core items are expected of every Python developer, recommended items are common in real jobs, and optional items can wait until you need them.
By the end you will write idiomatic, typed and tested Python, package it properly, and explain how the language works when an interviewer asks why. Solve problems in coding practice as you go and track your progress in progress page.
- Level
- Beginner to advanced
- Time
- 14–20 weeks at about 8 hours a week, less if you already program in another language
- Scope
- 61 topics in 10 stages
- Before you start
- No previous programming experience is required; Comfort with files, folders and a terminal; the Linux Roadmap and Shell and Bash Roadmap help; Basic maths: arithmetic, percentages and simple algebra; Git and GitHub Roadmap basics for saving and sharing your projects
What you will be able to do
- Write clear, idiomatic Python using the right built-in data structure for each job.
- Design programs with functions, modules and classes, and explain the data model behind them.
- Solve common interview problems in Python and state their time and space complexity.
- Add type hints, check them statically, and validate external data with Pydantic.
- Manage environments and dependencies with modern tools and publish a package.
- Write thorough tests with pytest, including fixtures, parametrisation and mocks.
- Choose between threads, processes and asyncio, and explain the GIL.
- Build a small web API with Flask or FastAPI and know when Django fits better.
The roadmap at a glance
- Stage 1Foundations: Syntax, Values and Control FlowBeginner · 2–3 weeks · 8 topics
- Stage 2Built-in Data StructuresBeginner · 2 weeks · 5 topics
- Stage 3Functions, Modules and ErrorsBeginner · 2 weeks · 8 topics
- Stage 4Object-Oriented PythonIntermediate · 2 weeks · 6 topics
- Stage 5Idiomatic Python: Iterators, Decorators and FilesIntermediate · 2 weeks · 6 topics
- Stage 6Data Structures and Algorithms in PythonIntermediate · 3–4 weeks · 6 topics
- Stage 7Typing and Code QualityIntermediate · 1–2 weeks · 4 topics
- Stage 8Environments, Packages and PackagingIntermediate · 1 week · 5 topics
- Stage 9TestingIntermediate · 1–2 weeks · 4 topics
- Stage 10Concurrency, Async and FrameworksAdvanced · 3–4 weeks · 9 topics
Stage 1 Foundations: Syntax, Values and Control Flow
Goal. Write small Python scripts that read input, make decisions, loop over data and print clear results.
Python and Your Setup Core
Python is a general-purpose, dynamically typed language that reads close to plain English. It is the usual first choice for scripting, automation, data work, machine learning and back-end services, and it is a common language in coding interviews because solutions stay short.
Install a current Python 3 release from the official installer or your system package manager. Python 2 reached end of life in 2020, so ignore tutorials that use print "x" without brackets. Learn three ways to run code: the interactive REPL (type python3), a script file (python3 app.py) and an editor such as VS Code or PyCharm with the Python extension, which gives you a debugger and inline errors.
CPython is the reference interpreter; it compiles source to bytecode and runs it on a virtual machine.
Practice. Install Python, open the REPL, and run a script that prints the interpreter version from sys.version.
Basic Syntax Core
Python uses indentation instead of braces to mark blocks. Four spaces per level is the convention; mixing tabs and spaces raises an error. A colon ends the line that opens a block, such as if, for, def or class. Statements end at the line break, so semicolons are not needed.
def greet(name):
if name:
print(f"Hello, {name}")
else:
print("Hello, stranger")
greet(input("Your name: "))Comments start with #. Names are case-sensitive and use snake_case for functions and variables, PascalCase for classes and UPPER_CASE for constants, as described in the PEP 8 style guide. The if __name__ == "__main__": guard lets a file act both as a script and as an importable module.
Practice. Write a script that asks for two numbers and prints their sum, using the __main__ guard.
Variables and Data Types Core
Variables in Python are names bound to objects. Assignment does not copy; it attaches a label. The object carries the type, not the name, so the same name can point to an int now and a string later. This is what dynamic typing means.
The built-in scalar types are int (arbitrary precision, so no overflow), float (64-bit binary floating point), complex, bool and None. Collection types are covered in the next stage.
a = [1, 2]
b = a # same list, two names
b.append(3)
print(a) # [1, 2, 3]
print(0.1 + 0.2 == 0.3) # False: binary floatsUse decimal.Decimal for money. Types are either mutable (list, dict, set) or immutable (int, str, tuple); this distinction explains many surprising bugs.
Practice. Show with id() that rebinding an int creates a new object while appending to a list does not.
Operators Core
Arithmetic operators include / for true division (always a float), // for floor division, % for remainder and ** for powers. Comparisons can chain: 0 < x <= 10. The logical operators and, or and not short-circuit and return one of their operands, which is why name or "guest" works as a default.
Know the difference between == (equal value) and is (same object). Use is only for None and other singletons. Membership uses in. The walrus operator := assigns inside an expression.
The @ symbol is also the matrix multiplication operator. Plain lists do not support it, but NumPy arrays do, so a @ b multiplies two matrices. Your own classes can support it by defining __matmul__.
Practice. Predict, then check, the output of 7 // -2, 7 % -2 and [] or "empty".
Typecasting Core
Typecasting in Python means calling a type as a function to build a new value of that type: int("42"), float("3.5"), str(10), list("abc"). Python does very little implicit conversion. It widens numbers in mixed arithmetic (int plus float gives float) but refuses "3" + 4 with a TypeError, which is why it is called strongly typed.
int("12") # 12
int(3.9) # 3, truncates toward zero
int("ff", 16) # 255
bool("") # False; any non-empty string is True
float("nan") # valid floatInvalid input raises ValueError, so wrap conversions of user data in try. Truthiness is a related idea: zero, empty collections, empty strings and None are false in conditions; almost everything else is true.
Practice. Write a function that turns a list of strings into integers and skips values that cannot be converted.
Conditionals Core
Conditionals use if, elif and else. Rely on truthiness for clean checks such as if items: rather than if len(items) > 0:. The conditional expression value = a if cond else b fits on one line.
Structural pattern matching, the match statement, compares a value against shapes, not only constants. It can unpack sequences, match dict keys and class attributes, and bind names.
match command.split():
case ["go", direction]:
move(direction)
case ["pick", "up", item]:
take(item)
case ["quit"] | ["exit"]:
stop()
case _:
print("Unknown command")A bare name in a case pattern captures a value instead of comparing to a variable, which is a common trap.
Practice. Write a grade function using if/elif, then a command parser using match.
Loops Core
The for loop iterates over any iterable: lists, strings, files, dictionaries and ranges. Use range(n) for counting, enumerate() when you need the index, and zip() to walk several sequences together. Avoid for i in range(len(xs)) unless you truly need the index for writing.
for i, name in enumerate(names, start=1):
print(i, name)
for key, value in prices.items():
...
while attempts < 3:
attempts += 1break leaves the loop and continue skips to the next pass. A loop can have an else block that runs only if the loop finished without break, which is handy for search loops. Do not add or remove items from a list while iterating over it; iterate over a copy or build a new list.
Practice. Print the first prime above 1,000 using a for/else search.
Working with Strings Core
Strings are immutable sequences of Unicode code points. You can index, slice (s[1:4], s[::-1]) and loop over them, but every change creates a new string. Building a long string in a loop with += can be slow; collect parts in a list and call "".join(parts).
Learn the common methods: split, strip, replace, startswith, lower, find and join. F-strings are the modern way to format: f"{total:,.2f}" adds separators and two decimals, and f"{x=}" prints a name and value for debugging.
Text (str) and raw bytes (bytes) are separate types. Convert with encode and decode, normally using UTF-8, at the edges of your program such as files and network sockets.
Practice. Write a function that checks whether a sentence is a palindrome, ignoring case, spaces and punctuation.
Stage 2 Built-in Data Structures
Goal. Choose the right built-in collection for a task and transform data with comprehensions.
Lists in Python Core
A list is an ordered, mutable sequence that can hold any objects. Under the hood it is a dynamic array of references, so indexing and append are fast (amortised constant time), while inserting or removing at the front is linear because everything after it shifts.
nums = [5, 2, 9]
nums.append(1)
nums.sort() # in place, returns None
top = sorted(nums, reverse=True) # new list
first, *rest = nums # unpacking
grid = [[0] * 3 for _ in range(3)] # not [[0]*3]*3Slicing returns a shallow copy. Copying a list of lists with list(x) still shares the inner lists; use copy.deepcopy when you need full independence. The last line above shows a classic bug: multiplying a list of lists repeats the same inner list.
Practice. Implement a function that rotates a list by k positions using slicing, then without slicing.
Tuples Core
A tuple is an ordered, immutable sequence. Use it for fixed groups of values where position has meaning, such as a coordinate or a database row, and for returning several values from a function. Because tuples of hashable items are themselves hashable, they can be dictionary keys and set members, which lists cannot.
point = (3, 4)
x, y = point
def min_max(xs):
return min(xs), max(xs) # returns a tuple
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: floatA one-item tuple needs a trailing comma: (5,). Immutability is shallow: a tuple holding a list can still see that list change. Named tuples add field names while keeping tuple behaviour, though dataclasses are often clearer for records.
Practice. Use tuples as keys in a dictionary that counts how often each (x, y) grid cell is visited.
Sets Core
A set is an unordered collection of unique, hashable items backed by a hash table. Membership tests take constant time on average, compared with a linear scan for a list, which makes sets the usual fix for slow if x in big_list checks.
seen = set()
for user in events:
if user in seen:
continue
seen.add(user)
a & b # intersection
a | b # union
a - b # in a but not bWrite an empty set as set(), because {} creates an empty dictionary. frozenset is the immutable version and can be used as a key. Sets do not keep insertion order, so convert to a sorted list when output order matters.
Practice. Given two lists of email addresses, print those that appear in exactly one of them.
Dictionaries Core
A dictionary maps hashable keys to values using a hash table, giving average constant-time lookup, insert and delete. Since Python 3.7 dictionaries keep insertion order as part of the language. They are the most used structure in Python: objects, modules and keyword arguments are all built on them.
ages = {"ana": 31, "li": 27}
ages.get("bob", 0) # default instead of KeyError
for name, age in ages.items(): ...
from collections import Counter, defaultdict
Counter("mississippi").most_common(2)
groups = defaultdict(list)
groups[team].append(player)
merged = defaults | overrides # 3.9+Keys must be immutable and hashable, so a list cannot be a key but a tuple can. Counter, defaultdict and OrderedDict from collections cover common counting and grouping needs.
Practice. Count word frequencies in a text file and print the ten most common, first with a plain dict, then with Counter.
List Comprehensions and Generator Expressions Core
List comprehensions build a list from an iterable in one readable expression, combining a loop, an optional filter and a transformation. The same syntax with braces creates sets and dictionaries.
squares = [n * n for n in range(10) if n % 2 == 0]
by_id = {u.id: u for u in users}
total = sum(n * n for n in range(10_000_000)) # generatorGenerator expressions use round brackets and produce values lazily, one at a time, instead of building the whole list in memory. Use them when you feed the result straight into sum, any, max or a loop. A generator can be consumed only once.
Keep comprehensions short. If you need nested loops with several conditions, a normal loop is easier to read and debug. Never use a comprehension only for its side effects.
Practice. Rewrite three of your earlier loops as comprehensions and measure memory with a list versus a generator over ten million items.
Stage 3 Functions, Modules and Errors
Goal. Organise code into functions and modules, handle failure clearly and use the standard library.
Functions Core
Functions are defined with def and are objects: you can pass them around, store them and return them. Parameters can be positional, keyword, defaulted, variadic (*args, **kwargs), positional-only (before /) or keyword-only (after *).
def connect(host, port=5432, *, timeout=10, **options):
...
connect("db", timeout=3, ssl=True)
def append_to(item, bucket=None): # not bucket=[]
bucket = [] if bucket is None else bucket
bucket.append(item)
return bucketDefault values are evaluated once, when the function is defined. A mutable default such as [] is shared between calls, a favourite interview question. Arguments are passed by object reference: the function receives the same object, so mutating it is visible to the caller, but rebinding the parameter is not.
Practice. Write a function with keyword-only flags and show the mutable default bug and its fix.
Variable Scope Core
Python resolves names with the LEGB rule: Local, Enclosing function, Global (module) and Built-in, in that order. Assigning to a name anywhere in a function makes it local for the whole function, which is why reading a global and then assigning to it raises UnboundLocalError.
count = 0
def bump():
global count # needed to rebind the module name
count += 1
def make_counter():
n = 0
def inc():
nonlocal n # rebind the enclosing variable
n += 1
return n
return incThe inner function above is a closure: it keeps access to n after make_counter returns. Closures look up variables when they run, not when they are created, so lambdas created in a loop all see the final loop value unless you bind it as a default argument. Prefer passing values and returning results over global.
Practice. Build a list of three lambdas in a loop, show that they all return the same value, and fix it.
Lambdas Recommended
A lambda is a small anonymous function written as a single expression: lambda x: x * 2. It cannot contain statements such as assignments or return. Lambdas are most useful as short arguments to functions that take a key or callback.
users.sort(key=lambda u: (u.last_name, u.age))
max(points, key=lambda p: p[0] ** 2 + p[1] ** 2)
from operator import itemgetter
rows.sort(key=itemgetter("price"))If you give a lambda a name (f = lambda x: ...), write a def instead; it gets a proper name in tracebacks and can have a docstring. map and filter with lambdas still work, but comprehensions are usually clearer. The operator module offers ready-made key functions.
Practice. Sort a list of dictionaries by two fields, one ascending and one descending.
Recursion Core
A recursive function calls itself on a smaller version of the problem until it reaches a base case. It is the natural fit for trees, nested data and divide-and-conquer algorithms such as merge sort.
def depth(node):
if node is None: # base case
return 0
return 1 + max(depth(node.left), depth(node.right))
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)CPython has no tail-call optimisation and limits recursion depth (around a thousand frames by default), so deep recursion raises RecursionError. Convert deep recursion to a loop with an explicit stack. Memoisation with functools.cache or lru_cache turns exponential recursive solutions into linear ones.
Practice. Write a recursive function that flattens arbitrarily nested lists, then an iterative version with a stack.
Modules and Custom Modules Core
Any .py file is a module, and a folder of modules is a package. Writing custom modules is how you split a growing script into files: put related functions in utils.py and import them elsewhere. A package traditionally has an __init__.py file, which runs on import and can expose a tidy public interface.
# shop/pricing.py
def with_tax(amount, rate=0.2):
return amount * (1 + rate)
# main.py
from shop.pricing import with_tax
import shop.pricing as pricingPython finds modules through sys.path, which includes the script's folder and installed packages. A module runs only once per process; later imports reuse the cached object in sys.modules. Avoid naming your files after standard modules such as random.py, and avoid circular imports by moving shared code into a third module. Prefer explicit imports over from x import *.
Practice. Split a single-file script into a small package with two modules and run it with python -m.
Builtin Modules and Common Packages Core
Python ships with a large standard library. The builtin modules you will meet constantly include os and pathlib for files and paths, sys for interpreter details, json and csv for data, datetime and zoneinfo for time, collections, itertools and functools for data and functional helpers, logging, argparse for command-line tools, subprocess, random and secrets.
Common packages and modules from outside the standard library that most Python developers know are requests or httpx for HTTP, NumPy and pandas for data, SQLAlchemy for databases, Pydantic for validation, pytest for tests, and Click or Typer for command-line interfaces.
Practice. Write a command-line tool with argparse that reads a CSV file and writes a JSON summary.
Error Handling and Exceptions Core
Python signals errors with exceptions. Code that might fail goes in try; except catches specific exception types; else runs if nothing was raised; finally always runs, which suits cleanup.
class InsufficientFunds(Exception):
pass
try:
amount = int(raw)
except ValueError as e:
raise InvalidInput(raw) from e
else:
account.withdraw(amount)
finally:
log.info("withdraw attempted")Catch the narrowest exception you can handle. A bare except: also swallows KeyboardInterrupt and hides bugs. Define your own exception classes for domain errors and use raise ... from to keep the original cause. Python favours EAFP, "easier to ask forgiveness than permission": try the operation and handle the failure, rather than checking every condition first. Exception groups and except* handle several errors raised together, mostly in async code.
Practice. Write a function that loads a JSON config file and raises a clear custom error when the file is missing or invalid.
Docstrings and Comments Recommended
Comments explain why the code does something unusual; the code should already say what it does. Docstrings are string literals placed first in a module, class or function. Python stores them in __doc__, and tools such as help(), editors and documentation generators read them.
def retry(fn, attempts=3):
"""Call fn until it succeeds or attempts run out.
Args:
fn: A function with no arguments.
attempts: Maximum number of calls.
Raises:
The last exception if every attempt fails.
"""Pick one docstring style, such as Google or NumPy style, and use it across the project. Sphinx is the long-standing tool for turning docstrings and reStructuredText or Markdown pages into an HTML documentation site; MkDocs is a popular Markdown-based alternative.
Practice. Add docstrings to a small module and view them with help() in the REPL.
Stage 4 Object-Oriented Python
Goal. Model problems with classes, use inheritance and composition sensibly, and make objects work with Python's built-in syntax.
Paradigms Recommended
Python supports several programming paradigms and lets you mix them. Procedural code is a sequence of functions acting on data, which suits scripts. Object-oriented programming (OOP) bundles data with the behaviour that acts on it, which suits long-lived systems with many related types. Functional style favours pure functions, immutable data and tools such as map, comprehensions, functools.reduce and itertools.
Good Python code usually combines them: functions for simple transformations, classes where state and invariants must stay together, and functional pipelines for data processing. Unlike Java, Python does not force everything into a class, so a module of plain functions is often the cleanest design.
Practice. Solve the same small task three ways, procedural, OOP and functional, and note which reads best.
Classes and OOP Basics Core
A class defines a new type; calling it creates an instance. __init__ initialises the new object, and self is the instance passed explicitly as the first parameter. Attributes set on self belong to the instance; attributes defined in the class body are shared by all instances.
class Account:
interest = 0.02 # class attribute
def __init__(self, owner, balance=0):
self.owner = owner # instance attribute
self.balance = balance
def deposit(self, amount):
self.balance += amount
@classmethod
def empty(cls, owner):
return cls(owner)
@staticmethod
def valid(amount):
return amount > 0Class methods receive the class and often act as alternative constructors; static methods receive neither and are plain functions grouped with the class. Mutable class attributes are shared, so a list defined in the class body is a common bug.
Practice. Model a library with Book and Member classes and a borrow method that enforces a limit.
Inheritance and Composition Core
Inheritance lets a subclass reuse and extend a parent class. Call the parent with super(). Python supports multiple inheritance and resolves attribute lookups with the method resolution order (MRO), visible through Cls.__mro__, using the C3 linearisation algorithm.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return f"{self.name} says woof"Use inheritance for a true "is a" relationship and keep hierarchies shallow. For "has a" relationships prefer composition: hold another object as an attribute and delegate to it. Abstract base classes from abc force subclasses to implement methods, and typing.Protocol describes an interface by shape without inheritance, matching Python's duck typing.
Practice. Refactor a deep inheritance tree of three levels into composition and compare the results.
Encapsulation Recommended
Python has no private keyword. Encapsulation works by convention: a single leading underscore (_cache) means internal, and other code should not touch it. A double leading underscore triggers name mangling (__x becomes _ClassName__x), which avoids accidental clashes in subclasses but is not real security.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius # goes through the setter
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = valueStart with plain public attributes. If you later need validation or a computed value, switch to @property without changing callers. Writing Java-style get_x and set_x methods is not idiomatic.
Practice. Add a validated property to a class without changing any code that uses it.
Methods and Dunder Methods Core
Dunder ("double underscore") methods let your objects work with built-in syntax and functions. Python calls __len__ for len(x), __eq__ for ==, __add__ for +, __iter__ for loops, __getitem__ for indexing and __enter__/__exit__ for with. Together these form the Python data model.
class Money:
def __init__(self, cents):
self.cents = cents
def __add__(self, other):
return Money(self.cents + other.cents)
def __eq__(self, other):
return isinstance(other, Money) and self.cents == other.cents
def __hash__(self):
return hash(self.cents)
def __repr__(self):
return f"Money({self.cents})"__repr__ should give an unambiguous developer view; __str__ gives a friendly one. If you define __eq__, define __hash__ too or instances become unhashable. Return NotImplemented for unsupported operand types.
Practice. Build a Vector class that supports +, * by a number, len(), equality and a readable repr.
Dataclasses Recommended
The dataclasses module generates __init__, __repr__ and __eq__ from annotated fields, removing boilerplate from classes that mainly hold data.
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class Order:
id: int
items: list[str] = field(default_factory=list)
total: float = 0.0frozen=True makes instances immutable and hashable, slots=True saves memory and blocks typos in attribute names, and order=True adds comparison methods. Use field(default_factory=list) for mutable defaults. Dataclasses do not validate types at run time; for parsing untrusted input use Pydantic, covered later. The third-party attrs library inspired dataclasses and offers more features.
Practice. Convert three plain classes from your project to dataclasses and remove the hand-written methods.
Stage 5 Idiomatic Python: Iterators, Decorators and Files
Goal. Write code that uses Python's protocols for iteration, resource handling and function wrapping, and process files and text.
Iterators and Generators Core
Iterators power every for loop. An iterable has __iter__, which returns an iterator; the iterator has __next__, which returns the next item or raises StopIteration. Lists are iterable but not iterators; files and generators are both.
A generator function contains yield. Calling it returns a generator object that runs the body only as values are requested, pausing at each yield. This lets you stream large files or infinite sequences in constant memory.
def read_rows(path):
with open(path) as f:
for line in f:
yield line.rstrip("\n").split(",")
from itertools import islice
for row in islice(read_rows("big.csv"), 5):
print(row)yield from delegates to another iterable. The itertools module offers chain, groupby, islice, product and batched for building pipelines.
Practice. Write a generator pipeline that reads a log file, filters error lines and yields parsed records.
Decorators Core
A decorator is a function that takes a function and returns a replacement, usually a wrapper that adds behaviour before or after the call. The @name line above a definition is shorthand for f = name(f). Decorators are used for logging, timing, caching, retries, access checks and registering routes in web frameworks.
import functools, time
def timed(fn):
@functools.wraps(fn) # keep name and docstring
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
print(fn.__name__, time.perf_counter() - start)
return wrapperA decorator that takes arguments, such as @retry(times=3), needs one more level: a function that returns the decorator. Decorators rely on closures and on functions being objects, so explaining one well shows you understand both.
Practice. Write a @retry(times, delay) decorator and test it on a function that fails randomly.
Context Manager Core
A context manager sets something up and guarantees cleanup when a with block ends, even if an exception is raised. Files, locks, database transactions and temporary directories all use this protocol.
from contextlib import contextmanager
@contextmanager
def transaction(conn):
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raiseA class becomes a context manager by defining __enter__ and __exit__; returning true from __exit__ suppresses the exception, so do that only on purpose. The contextlib.contextmanager decorator shown above is the shorter route. contextlib also offers suppress, ExitStack for a variable number of resources, and async versions for async with.
Practice. Write a context manager that changes the working directory and always restores it.
File Handling in Python Core
Open files with open() inside a with block so they always close. Mode "r" reads, "w" truncates and writes, "a" appends and "x" creates only if missing; add "b" for binary. Always pass encoding="utf-8" for text, because the default depends on the platform.
from pathlib import Path
path = Path("data") / "report.txt"
path.parent.mkdir(exist_ok=True)
path.write_text("done\n", encoding="utf-8")
with path.open(encoding="utf-8") as f:
for line in f: # streams, line by line
process(line)pathlib.Path is the modern way to build and inspect paths, replacing most os.path calls. Iterate over a file object rather than calling read() on large files. Use the json, csv and tomllib modules instead of parsing these formats by hand.
Practice. Write a script that merges every CSV file in a folder into one, keeping a single header row.
Glob Module in Python Recommended
The glob module in Python finds file paths that match shell-style wildcards: * matches any characters, ? matches one, and [abc] matches a set. With recursive=True, ** also matches nested folders.
import glob
logs = glob.glob("logs/**/*.log", recursive=True)
from pathlib import Path
for p in Path("src").rglob("*.py"):
print(p, p.stat().st_size)Results are not sorted, so call sorted() if order matters. Hidden files that start with a dot are skipped by default. In new code, Path.glob() and Path.rglob() do the same job and return Path objects. For matching names you already have, use fnmatch.
Practice. List the five largest Python files in a project using rglob.
Regular Expressions Recommended
The re module matches text against patterns. Write patterns as raw strings (r"\d+") so backslashes reach the regex engine unchanged. re.search finds the first match anywhere, re.match only at the start, re.fullmatch the whole string, re.findall all matches and re.sub replaces.
import re
DATE = re.compile(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})")
m = DATE.search("Due 2024-05-01, paid later")
if m:
print(m["y"], m.group("m"))Named groups make patterns readable. Quantifiers are greedy by default; add ? for the shortest match. Compile patterns you reuse. Do not use regex to parse HTML or JSON; use a real parser. Badly written patterns with nested quantifiers can take exponential time on some inputs.
Practice. Extract all email addresses and phone numbers from a text file into two sorted lists.
Stage 6 Data Structures and Algorithms in Python
Goal. Implement and analyse the core data structures and algorithms that coding interviews test, using Python's built-ins well.
Data Structures and Algorithms Core
Coding interviews test whether you can choose a data structure, write a correct algorithm and state its time and space complexity in Big O notation. Python is a strong interview language because its built-ins already provide most structures: list as a dynamic array and stack, dict as a hash map, set, collections.deque as a queue, and heapq as a priority queue.
Know the costs: list index and append are O(1), insert at the front and x in list are O(n), dict and set lookups are O(1) on average, and sorting is O(n log n). The Data Structures and Algorithms Roadmap covers the common patterns in depth.
Practice. Solve five easy array and string problems in coding practice and write the complexity of each.
Arrays and Linked lists Core
Arrays and linked lists are the two basic ways to store a sequence. An array keeps items next to each other, so indexing is O(1) but inserting in the middle shifts everything. A Python list is a dynamic array of references; the array module and NumPy store raw numbers compactly.
class Node:
def __init__(self, val, next=None):
self.val, self.next = val, next
def reverse(head):
prev = None
while head:
head.next, prev, head = prev, head, head.next
return prevA linked list stores nodes that point to the next node, so inserting after a known node is O(1) but finding the k-th item is O(n). Python has no built-in linked list, so interviewers ask you to write one. Practise reversal, cycle detection with fast and slow pointers, and merging two sorted lists.
Practice. Implement a singly linked list with append, delete and reverse, and detect a cycle with two pointers.
HashMaps Core
HashMaps store key-value pairs and find a key by hashing it to a bucket index. In Python the dict is the hash map. Average lookup, insert and delete are O(1); in the worst case, when many keys collide, they degrade towards O(n). CPython uses open addressing with a compact, insertion-ordered layout.
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return seen[target - n], i
seen[n] = iHash maps turn many O(n squared) brute-force solutions into O(n) ones, as in the classic two-sum problem above. Keys must be hashable and their hash must not change while stored, which is why mutable objects make poor keys. Be ready to explain hashing, collisions and resizing.
Practice. Solve "group anagrams" and "longest substring without repeating characters" with dictionaries.
Heaps, Stacks, and Queues Core
Heaps, stacks, and queues control the order in which items come out. A stack is last in, first out: use a list with append and pop. A queue is first in, first out: use collections.deque with append and popleft, both O(1). Popping from the front of a list is O(n).
import heapq
from collections import deque
h = []
heapq.heappush(h, (priority, task))
priority, task = heapq.heappop(h) # smallest first
top3 = heapq.nlargest(3, scores)
q = deque([start])
node = q.popleft()A heap keeps the smallest item at the front with O(log n) push and pop. heapq is a min-heap; store negated values for a max-heap. Typical uses are top-k problems, merging sorted streams and Dijkstra's algorithm. For thread-safe queues use queue.Queue.
Practice. Find the k most frequent words with a heap, and check balanced brackets with a stack.
Binary Search Trees Core
Binary search trees keep, for every node, smaller values in the left subtree and larger values in the right. Search, insert and delete take O(height): O(log n) when the tree is balanced and O(n) when it degenerates into a chain, for example after inserting sorted data. Self-balancing variants such as red-black and AVL trees keep the height logarithmic.
def insert(node, val):
if node is None:
return Node(val)
if val < node.val:
node.left = insert(node.left, val)
else:
node.right = insert(node.right, val)
return nodeAn in-order traversal returns the values sorted, which is the basis of the "validate a BST" question. Python has no built-in balanced tree; the third-party sortedcontainers package fills that gap.
Practice. Implement insert, search and in-order traversal, then write a function that validates a BST.
Sorting Algorithms Core
Python's built-in sorted() and list.sort() use Timsort (Powersort in recent CPython), a stable hybrid of merge sort and insertion sort that runs in O(n log n) and is very fast on partly sorted data. Stable means equal items keep their original order, which lets you sort by several keys in passes.
def merge_sort(xs):
if len(xs) <= 1:
return xs
mid = len(xs) // 2
left, right = merge_sort(xs[:mid]), merge_sort(xs[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]Interviews still ask you to write and compare merge sort, quicksort (average O(n log n), worst O(n squared), in place) and heap sort, and to know when counting sort beats them. In real code always use the built-in with a key function.
Practice. Implement quicksort and merge sort, then compare their speed against sorted() on a million numbers.
Stage 7 Typing and Code Quality
Goal. Add type hints, check them with a static checker, validate data at the edges, and keep code consistently formatted and documented.
Type Annotations and Typing Core
Type annotations describe the expected types of variables, parameters and return values. Python ignores them at run time; they are read by editors and static checkers. Modern syntax uses built-in generics and the | operator.
def find_user(users: dict[int, str], uid: int) -> str | None:
return users.get(uid)
from typing import Protocol
class Closer(Protocol):
def close(self) -> None: ...
def first[T](items: list[T]) -> T: # 3.12 generic syntax
return items[0]The typing module adds Protocol for structural interfaces, TypedDict for dictionary shapes, Literal, Callable, Final and TypeVar. Older code uses List[int] and Optional[str] from typing; these still work but are no longer needed. Annotate public functions first; local variables are usually inferred.
Practice. Add complete type hints to a module of five functions and a class.
Static Typing Tools: mypy, pyright and pyrefly Recommended
Static typing in Python is optional and gradual: you add hints over time, and a checker reads the code without running it to find mismatches such as passing None where a string is required. mypy is the original checker and is configured in pyproject.toml; strict mode catches the most. pyright, from Microsoft, is fast and powers type checking in VS Code through Pylance.
pyrefly is a newer checker from Meta written in Rust, aimed at very large codebases and fast editor feedback; Astral's ty is another Rust-based newcomer. Pick one per project and run it in CI.
[tool.mypy]
strict = true
python_version = "3.12"
Practice. Run mypy in strict mode on your project and fix every reported error without using Any.
Pydantic Recommended
Pydantic validates and parses data at run time using type hints. You declare a model as a class with annotated fields; creating an instance converts compatible input and raises a detailed error for invalid data. This makes it the standard choice for checking API requests, configuration and data from files.
from pydantic import BaseModel, EmailStr, Field
class SignUp(BaseModel):
email: EmailStr
age: int = Field(ge=13)
tags: list[str] = []
user = SignUp.model_validate({"email": "a@b.io", "age": "30"})
print(user.age + 1) # 31, string was converted
print(user.model_dump_json())Pydantic version 2 has a core written in Rust and renamed many methods: parse_obj became model_validate and dict() became model_dump(). FastAPI uses Pydantic models for request bodies and responses, and pydantic-settings loads typed settings from environment variables.
Practice. Define a Pydantic model for an order and print the error messages for three kinds of invalid input.
Code Formatting and Linting: black, ruff and yapf Recommended
Code formatting tools rewrite your files to a consistent style so reviews focus on logic instead of spacing. black is the opinionated formatter with almost no options. yapf, from Google, is a configurable formatter based on a style you choose. ruff, written in Rust, is both a very fast linter, replacing flake8, isort, pyupgrade and many plugins, and a formatter compatible with black.
[tool.ruff]
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]
$ ruff check --fix .
$ ruff format .Many new projects use ruff alone. Linters find real bugs, such as unused variables, mutable defaults and shadowed names. Run the formatter on save in your editor and as a pre-commit hook, and fail the build in CI if files are not formatted.
Practice. Add ruff to a project, enable import sorting and bug-finding rules, and set up a pre-commit hook.
Stage 8 Environments, Packages and Packaging
Goal. Isolate project dependencies, choose a package manager, and build and publish a package with pyproject.toml.
Pip and PyPI Core
PyPI, the Python Package Index, is the public repository of Python packages. pip is the standard installer that downloads packages from it, along with their dependencies. Always run it as python -m pip so it installs into the interpreter you expect.
python -m pip install "requests>=2.31,<3"
python -m pip install -r requirements.txt
python -m pip freeze > requirements.txt
python -m pip list --outdatedPackages are distributed as wheels (pre-built archives, fast to install) or source distributions. Pin exact versions for applications to get reproducible installs; libraries should declare looser ranges. Never install packages into the system Python with sudo; many Linux distributions now block this.
Practice. Install three packages into a project, freeze them, and reinstall from the file in a fresh environment.
virtualenv and venv Core
A virtual environment is a folder with its own Python executable and site-packages, so each project has separate dependencies and versions do not clash. The built-in venv module creates one; virtualenv is the older third-party tool with the same purpose and a few extra features, such as faster creation.
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
deactivateActivation only adjusts your shell's PATH; you can also call .venv/bin/python directly. Add .venv to .gitignore and recreate it from your dependency file instead of copying it. Most modern tools create and manage the environment for you.
Practice. Create two environments with different versions of the same library and show both working.
Package Managers: Poetry, PDM, pipenv and uv Recommended
Package managers add dependency resolution, lock files and environment handling on top of pip. pipenv combined a Pipfile with a virtual environment and was popular for a while. Poetry manages dependencies, lock files, building and publishing through pyproject.toml. PDM is a standards-focused alternative with similar features.
uv, from Astral and written in Rust, is now a common default for new projects. It is much faster than pip, creates environments automatically, writes a lock file, and can install Python versions itself.
uv init myapp && cd myapp
uv add httpx pydantic
uv add --dev pytest ruff
uv run pytest
uv lockA lock file records exact versions of every transitive dependency, so all machines install the same set. Commit it for applications. In an interview, explain the problem they solve rather than which tool is best.
Practice. Start a new project with uv, add runtime and development dependencies, and run its tests through uv run.
pyenv and Conda Optional
pyenv installs and switches between several Python versions on one machine, per user or per folder, through a .python-version file. It is useful when projects need different interpreters; uv can now handle this job too.
Conda is a separate package and environment manager common in data science. It installs Python itself and non-Python dependencies such as compiled C, CUDA and Fortran libraries, from its own channels like conda-forge. Miniforge is a small installer that defaults to conda-forge.
pyenv install 3.12
pyenv local 3.12
conda create -n ds python=3.12 numpy pandas
conda activate dsOutside data and scientific work, venv with pip or uv is usually enough.
Practice. Use pyenv or uv to run the same test suite on two Python versions.
pyproject.toml and Publishing Recommended
pyproject.toml is the standard configuration file for Python projects. It declares the build system, project metadata and dependencies, and most tools (ruff, mypy, pytest, black) read their settings from it. It replaces setup.py and setup.cfg for most projects.
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "tinycsv"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = ["click>=8"]
[project.scripts]
tinycsv = "tinycsv.cli:main"Use a src/ layout so tests run against the installed package. Build wheels with python -m build or uv build, try them on TestPyPI, then upload with twine or uv publish using trusted publishing from CI.
Practice. Package a small command-line tool with a console script entry point and install it from the built wheel.
Stage 9 Testing
Goal. Write fast, reliable tests with pytest, isolate external dependencies, and run them across environments.
Testing Basics and PyUnit / unittest Core
Testing gives you the confidence to change code. Unit tests check one function or class in isolation; integration tests check pieces working together, such as code plus a real database; end-to-end tests drive the whole application.
PyUnit / unittest is the testing framework in the standard library, modelled on Java's JUnit. Tests are methods on a class that subclasses unittest.TestCase, with setUp and tearDown for fixtures and assertion methods such as assertEqual and assertRaises.
import unittest
class TestSlugify(unittest.TestCase):
def test_spaces(self):
self.assertEqual(slugify("Hello World"), "hello-world")
if __name__ == "__main__":
unittest.main()You will meet unittest in older codebases. pytest can run unittest tests unchanged, so migration can be gradual.
Practice. Write a unittest test case with three tests for a string utility and run it with python -m unittest.
pytest Core
pytest is the most widely used Python test framework. Tests are plain functions whose names start with test_, and you use the normal assert statement; pytest rewrites it to show detailed failure messages.
import pytest
@pytest.fixture
def cart():
return Cart()
@pytest.mark.parametrize("qty,total", [(1, 10), (3, 30), (0, 0)])
def test_total(cart, qty, total):
cart.add("pen", price=10, qty=qty)
assert cart.total() == total
def test_negative(cart):
with pytest.raises(ValueError):
cart.add("pen", price=10, qty=-1)Fixtures supply set-up objects and can be scoped per test, module or session; shared ones live in conftest.py. parametrize runs one test over many inputs. Plugins add coverage (pytest-cov) and parallel runs. Tox runs the suite in several isolated environments, such as three Python versions; a CI matrix often does this job now.
Practice. Write a parametrised pytest suite with a fixture for a shopping cart and report coverage.
Mocking and Test Doubles Recommended
Mocks replace slow or unpredictable dependencies, such as HTTP calls, the clock or a payment API, with objects you control. unittest.mock provides Mock, MagicMock and patch.
from unittest.mock import patch
def test_weather(monkeypatch):
with patch("app.weather.httpx.get") as fake:
fake.return_value.json.return_value = {"temp": 21}
assert describe("Paris") == "Mild"
fake.assert_called_once()Patch the name where it is looked up, not where it is defined: if app/weather.py does import httpx, patch app.weather.httpx. Use autospec=True so mocks reject calls that the real object would not accept. Too many mocks make tests fragile; prefer passing dependencies in as arguments and using simple fakes.
Practice. Test a function that calls an external API by patching the HTTP client and asserting on the arguments it received.
Doctest Optional
Doctest runs the interactive examples written in docstrings and checks that the output matches. It keeps documentation honest: if the behaviour changes, the example fails.
def add(a, b):
"""Return the sum.
>>> add(2, 3)
5
>>> add("a", "b")
'ab'
"""
return a + bRun it with python -m doctest module.py -v or with pytest --doctest-modules. Doctest compares printed text exactly, so it suits small, deterministic examples but not complex logic, unordered output or anything involving time. Use it alongside a real test suite, not instead of one.
Practice. Add doctest examples to three functions and run them through pytest.
Stage 10 Concurrency, Async and Frameworks
Goal. Pick between threads, processes and async I/O, explain the GIL, and build a small web API with a Python framework.
Concurrency and the GIL Core
Concurrency means making progress on several tasks at once; parallelism means running them at the same instant on several cores. Python offers threads, processes and async coroutines.
The GIL, the global interpreter lock, lets only one thread execute Python bytecode at a time in standard CPython. It keeps reference counting simple and safe. As a result, threads speed up I/O-bound work (waiting on networks, disks or databases releases the GIL) but not CPU-bound pure Python code. C extensions such as NumPy release the GIL during heavy work.
Recent CPython versions offer an optional free-threaded build without the GIL, first as an experimental build and now officially supported, though not the default. The rule of thumb stays: threads or async for I/O-bound work, processes for CPU-bound work.
Practice. Time a CPU-bound function run on four threads versus four processes and explain the difference.
Threading Recommended
The threading module runs functions in OS threads that share memory. The simplest safe API is concurrent.futures.ThreadPoolExecutor, which manages a pool and returns futures.
from concurrent.futures import ThreadPoolExecutor
import threading, httpx
lock = threading.Lock()
done = 0
def fetch(url):
global done
r = httpx.get(url, timeout=10)
with lock: # += is not atomic
done += 1
return r.status_code
with ThreadPoolExecutor(max_workers=8) as pool:
codes = list(pool.map(fetch, urls))The GIL does not make your code thread-safe: operations like += span several bytecodes and can interleave. Protect shared state with a Lock, or avoid sharing by passing data through a queue.Queue. Watch for deadlocks when taking several locks.
Practice. Download twenty pages sequentially and with a thread pool, and compare the times.
Multiprocessing Recommended
The multiprocessing module starts separate Python processes, each with its own interpreter and GIL, so CPU-bound work can use every core. ProcessPoolExecutor offers the same interface as the thread pool.
from concurrent.futures import ProcessPoolExecutor
def score(chunk):
return sum(expensive(x) for x in chunk)
if __name__ == "__main__": # required on Windows and macOS
with ProcessPoolExecutor() as pool:
total = sum(pool.map(score, chunks))Processes do not share memory by default. Arguments and results are pickled and copied between processes, so send a few large chunks rather than many tiny tasks. The __main__ guard is required where new processes are started by spawning a fresh interpreter. For shared data, use multiprocessing.shared_memory or a Manager, at a cost.
Practice. Parallelise image resizing or prime counting across all cores and measure the speed-up.
Asynchrony with asyncio Core
Asynchrony lets one thread juggle thousands of I/O tasks. An async def function returns a coroutine; await pauses it until a result is ready, letting the event loop run others meanwhile. It suits servers, crawlers and anything spending most of its time waiting on the network.
import asyncio, httpx
async def fetch(client, url):
r = await client.get(url)
return r.status_code
async def main(urls):
async with httpx.AsyncClient() as client:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(client, u)) for u in urls]
return [t.result() for t in tasks]
asyncio.run(main(urls))Never call blocking functions such as time.sleep or requests.get inside a coroutine; they freeze the loop. Use async libraries, or asyncio.to_thread for blocking code. TaskGroup cancels sibling tasks when one fails. Limit concurrency with a Semaphore and set timeouts with asyncio.timeout.
Practice. Write an async crawler that fetches 100 URLs with at most ten requests in flight.
Async Libraries: AIOHTTP and gevent Optional
AIOHTTP is an asyncio-based HTTP client and server library. Its client was the standard async choice for years and is still common; httpx now offers a similar async client with a requests-like interface.
import aiohttp
async def get(url):
async with aiohttp.ClientSession() as s:
async with s.get(url) as r:
return await r.text()gevent takes a different route. It uses green threads, lightweight coroutines switched in user space, and "monkey-patches" standard library modules such as socket so ordinary blocking code becomes cooperative without async/await. It is found in older services and with Gunicorn workers. The patching is global and can surprise libraries, so new projects normally choose asyncio.
Practice. Rewrite the async crawler with an AIOHTTP session and compare the code with the httpx version.
Python Frameworks Overview Recommended
Python frameworks fall into a few groups. Full-stack web frameworks such as Django include an ORM, templating, admin and authentication. Micro-frameworks such as Flask give you routing and leave the rest to you. Async API frameworks such as FastAPI and Sanic build on asyncio for high concurrency.
Older or niche choices still appear. Pyramid is a flexible framework with a much smaller community today. Tornado is an early async web framework and networking library, predating asyncio, still used for long-lived connections. Plotly Dash builds interactive data dashboards in pure Python, popular with analysts.
Choose by need: admin-heavy product with a relational database, Django; typed JSON API, FastAPI; small service or prototype, Flask.
Practice. Write a one-paragraph recommendation of a framework for three different example projects.
Django Recommended
Django is the "batteries included" web framework. A project contains apps; each app has models (database tables defined as Python classes), views (functions or classes that handle requests), URL routes and templates. The ORM generates SQL and migrations, and the admin site gives you a back office for free.
class Post(models.Model):
title = models.CharField(max_length=200)
published = models.DateTimeField(null=True)
# views.py
def latest(request):
posts = Post.objects.filter(published__isnull=False)[:10]
return render(request, "blog/latest.html", {"posts": posts})Django provides protection against SQL injection, cross-site scripting and CSRF by default. Django REST Framework is the common way to build APIs on top. Learn select_related and prefetch_related to avoid the N+1 query problem. The Django Roadmap covers it fully.
Practice. Build a small blog with Django models, the admin and one list view.
Flask Recommended
Flask is a lightweight framework that gives you routing, request handling and Jinja templates, and lets you choose everything else, such as the ORM, forms and authentication, through extensions like Flask-SQLAlchemy and Flask-Login.
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.post("/notes")
def create_note():
data = request.get_json()
note = save(data["text"])
return jsonify(id=note.id), 201It runs on WSGI, the synchronous interface between Python apps and web servers such as Gunicorn. Larger apps use blueprints.
Practice. Build a notes JSON API in Flask with create, list and delete endpoints and pytest tests.
FastAPI Recommended
FastAPI builds HTTP APIs from type-hinted functions. It uses Pydantic models to validate requests and serialise responses, generates OpenAPI documentation automatically, and supports both async def and normal handlers. It runs on ASGI servers such as Uvicorn.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items", status_code=201)
async def create(item: Item) -> Item:
if item.price <= 0:
raise HTTPException(422, "price must be positive")
return itemDependency injection with Depends handles database sessions and authentication. Normal def handlers run in a thread pool, so blocking code is safe there but not inside async def. Sanic is a similar async framework with its own server.
Practice. Build a FastAPI service with Pydantic models, a dependency for the database session and generated docs.
Projects to build
Build these in order. Each one should end up in a public repository with a short README that explains your decisions.
- Command-line expense trackerBeginner
Build a command-line tool that adds, lists and summarises expenses by category and month, storing data in a JSON or CSV file. Use
argparsefor commands and handle bad input with clear messages.Basic syntax · Dictionaries · File handling · Error handling · argparse
- Log analyser libraryIntermediate
Write a package that streams large log files with generators, parses lines with regular expressions and reports error rates per hour. Add type hints, a pytest suite with fixtures and a
pyproject.toml, and make it installable as a command.Generators · Regular expressions · Typing · pytest · Packaging
- Async link checkerIntermediate
Crawl a website starting from one URL, follow internal links, and report broken ones. Use asyncio with an HTTP client, a semaphore to limit concurrency, timeouts and retries with a decorator. Compare the run time with a thread-pool version.
asyncio · Threading · Decorators · Sets · Error handling
- Task API with FastAPIAdvanced
Build a REST API for tasks with users, authentication, Pydantic models and a SQL database through SQLAlchemy. Write unit and integration tests, lint and type-check it in CI, and run it in a container.
FastAPI · Pydantic · pytest · mypy · uv
- Data structures toolkitAdvanced
Implement a linked list, binary search tree, min-heap and LRU cache from scratch with full type hints and dunder methods so they work with
len,inand iteration. Benchmark them against the built-ins and document the complexity of every operation.Data structures · Dunder methods · Iterators · Testing · Big O
Interview questions
Try to answer each question out loud before you open the answer.
What is the difference between a list and a tuple?Junior
Both are ordered sequences. A list is mutable, so you can append, remove and change items; a tuple is immutable once created. Because of that, a tuple of hashable values is hashable and can be a dictionary key or a set member, while a list cannot. I use tuples for fixed records and multiple return values, and lists for collections that grow or change. Tuples are also slightly smaller in memory.
Why is a mutable default argument a problem?Junior
Default values are evaluated once, when the def statement runs, not on each call. A default like items=[] is therefore one list shared across every call that omits the argument, so data leaks from one call to the next. The fix is to default to None and create a new list inside the function. Linters flag this pattern.
What is the difference between == and is?Junior
== compares values by calling __eq__; is checks whether two names refer to the same object. Two separate lists with equal contents are == but not is. I use is only for singletons such as None. Small integers and some strings are cached by CPython, so is can appear to work on them, but relying on that is a bug.
How are arguments passed to functions in Python?Junior
By object reference, sometimes called pass by assignment. The parameter becomes a new name for the same object the caller passed. If the function mutates that object, such as appending to a list, the caller sees the change. If it rebinds the parameter to a new object, the caller does not. Immutable objects like ints and strings therefore behave as if passed by value.
Explain list comprehensions versus generator expressions.Junior
A list comprehension builds the whole list in memory immediately. A generator expression has the same syntax with round brackets but produces items lazily, one at a time, when something iterates over it. For a large or infinite input, or when the result goes straight into sum or any, the generator uses constant memory. A list is better when you need indexing, the length or several passes, since a generator can be consumed only once.
How do dictionaries work internally, and what can be a key?Mid
A dict is a hash table. Python hashes the key, uses the hash to find a slot and compares keys with == on collision, which gives average O(1) lookups. CPython keeps a compact array of entries in insertion order plus a sparse index table. Keys must be hashable, meaning their hash never changes and equal objects have equal hashes, so immutable types such as strings, numbers and tuples of hashables work, but lists and dicts do not.
What is a decorator? Write one.Mid
A decorator is a callable that takes a function and returns a replacement, normally a wrapper adding behaviour around the original call. @timed above a function means f = timed(f). Inside, I define wrapper(*args, **kwargs), run code before and after calling the original, and apply functools.wraps to keep its name and docstring. A decorator with arguments adds one more outer function that returns the decorator. It works because functions are objects and closures remember variables.
What is a generator and when would you use one?Mid
A generator is a function containing yield. Calling it returns an iterator that runs the body lazily, pausing at each yield and resuming on the next request, keeping its local state. I use generators to stream large files, build processing pipelines and represent infinite sequences without holding everything in memory. They implement the iterator protocol, so they work anywhere an iterable is expected.
What is the GIL and how does it affect concurrency?Mid
The global interpreter lock lets only one thread run Python bytecode at a time in standard CPython, which keeps reference counting and the interpreter simple. Threads still help I/O-bound work, because the GIL is released while waiting on network or disk, but CPU-bound pure Python code does not speed up with threads. For CPU work I use multiprocessing or libraries like NumPy that release the GIL. Newer CPython has an optional free-threaded build, but it is not the default.
When would you choose threads, processes or asyncio?Senior
For CPU-bound work, processes, because each has its own interpreter and GIL. For I/O-bound work with a moderate number of tasks or blocking libraries, a thread pool is simplest. For many concurrent network connections, such as a server or crawler with thousands of requests, asyncio uses one thread efficiently, but every library in the path must be async-aware. I also consider the cost: processes copy data, threads need locks on shared state, and async needs discipline about blocking calls.
Explain what a context manager is and how you would write one.Mid
A context manager guarantees setup and teardown around a block of code through the with statement, even if the block raises. It implements __enter__, whose return value is bound by as, and __exit__, which receives exception details and can suppress them by returning true. The shorter way is contextlib.contextmanager: a generator that yields once, with cleanup in a finally. Typical uses are files, locks, transactions and temporarily changing settings.
What are dunder methods? Give examples.Mid
Dunder methods are special methods with double underscores that Python calls to implement built-in behaviour. __init__ initialises instances, __repr__ and __str__ give text forms, __eq__ and __hash__ define equality and hashing, __len__ and __getitem__ make an object behave like a sequence, __iter__ makes it iterable, and __enter__/__exit__ make it a context manager. Implementing them makes custom classes feel native.
How does Python manage memory?Senior
CPython mainly uses reference counting: every object tracks how many references point to it and is freed when the count reaches zero. Reference cycles, such as two objects pointing at each other, are collected by a separate generational garbage collector in the gc module. Small objects come from a specialised allocator. I can find leaks with tracemalloc, and use weakref for caches that should not keep objects alive.
How do you structure and manage dependencies in a Python project?Mid
I use a pyproject.toml with a src/ layout, a virtual environment per project and a tool such as uv or Poetry that writes a lock file. Applications pin exact versions through the lock file; libraries declare compatible ranges. Development tools like pytest, ruff and mypy go in a dev dependency group. CI installs from the lock file, runs lint, type checks and tests, and a tool like Dependabot proposes updates.
How would you speed up a slow Python program?Senior
I measure first, using cProfile or a sampling profiler to find the hot spots rather than guessing. Then I fix the algorithm or data structure, for example replacing list membership with a set or a nested loop with a dict. Next I use built-ins and libraries implemented in C, such as NumPy, add caching for repeated work, and batch I/O. For CPU-bound work I parallelise with processes. Only after that would I consider compiled extensions or alternative interpreters.
Common mistakes
- Using a mutable default argument such as
[]or{}; default toNoneand create the object inside the function. - Writing a bare
except:orexcept Exception: pass, which hides bugs; catch specific exceptions and log or re-raise. - Installing packages globally with
sudo pip; use a virtual environment or uv for every project. - Checking membership in a large list inside a loop; convert it to a set or dict first.
- Modifying a list while iterating over it; iterate over a copy or build a new list with a comprehension.
- Calling blocking functions like
time.sleeporrequests.getinside async code; use async libraries orasyncio.to_thread. - Expecting threads to speed up CPU-heavy pure Python code; use processes or vectorised libraries instead.
- Opening files without
withor without an explicit encoding; use awithblock andencoding="utf-8". - Skipping tests and type hints until the project is large; add pytest and a type checker from the first module.
Ready-for-interview checklist
- I can explain mutability, references and why
a = bdoes not copy a list. - I can choose between a list, tuple, set, dict and deque and state the cost of their main operations.
- I can write comprehensions and generators and explain when each is the better choice.
- I can write a decorator with arguments and a context manager from memory.
- I can design a small class hierarchy and explain the MRO, properties and key dunder methods.
- I can implement a linked list, BST and heap-based solution and analyse their complexity.
- I can solve medium array, string and hash map problems in Python within 30 minutes.
- I can add type hints to a module and get a clean mypy or pyright run.
- I can set up a project with pyproject.toml, a virtual environment and a lock file.
- I can write pytest tests with fixtures, parametrisation and mocks.
- I can explain the GIL and choose threads, processes or asyncio for a workload.
- I can build and test a small REST API with FastAPI or Flask.
Related roadmaps
- Data Structures and Algorithms RoadmapFrom arrays to graphs and DP, organised by interview pattern.
- Django RoadmapModels, views, the ORM, auth, REST APIs and deployment.
- Python for Data Analysis RoadmapNumPy, pandas, cleaning, visualisation and notebooks.
- SQL RoadmapQueries, joins, window functions, indexes and transactions.
- Docker RoadmapImages, containers, networking, volumes, Compose and security.
- API Design RoadmapREST, gRPC, GraphQL, versioning, auth, pagination and rate limits.
FAQ
How long does it take to learn Python?
Most beginners can write useful scripts after four to six weeks of regular practice. Reaching junior interview level, including object-oriented design, testing, packaging and solving medium coding problems, usually takes four to five months at around eight hours a week. If you already program in another language, expect a few weeks to become productive and a couple of months to become idiomatic.
Is Python a good first programming language?
Yes. Its syntax is short and readable, errors are usually clear, and you can see results quickly in the REPL. It also stays useful as you advance, from scripts to web services to machine learning. The main things it hides, such as memory management and static types, are worth learning later through a language like Java, Go or C.
Should I learn Django, Flask or FastAPI first?
Learn core Python first. Then pick by goal: FastAPI if you want to build typed JSON APIs, Django if you want a complete web application with an admin and ORM, and Flask if you want to understand the basics of web apps with little hidden. The concepts transfer, so the first framework matters less than building something real with it.
Is Python fast enough for real applications?
For most web services, automation and data work, yes, because the bottleneck is usually the network, the database or a C library rather than Python itself. Pure Python loops are slower than compiled languages, so heavy numerical work uses NumPy or similar libraries. When raw speed matters across a whole service, teams pick Go, Rust or Java for that part.