A quick-reference cheatsheet for the most commonly used Python features. Python is a dynamically typed, interpreted language that emphasises readability. Everything is an object, functions are first-class, and the standard library covers most everyday needs without extra dependencies.
These are always available without importing. They cover the most common operations on iterables, types, and I/O. Prefer them over manual loops where possible โ they are implemented in C and clearly communicate intent.
Print:print("hello", end="\n", sep=" ")
(end and sep are optional kwargs)
Type & isinstance:type(x) / isinstance(x, int)
(isinstance also accepts a tuple of types)
Range:range(start, stop, step)
(stop is exclusive; step defaults to 1)
Enumerate:for i, val in enumerate(iterable, start=0):
(yields (index, value) tuples; avoids manual counter)
Zip:for a, b in zip(list1, list2):
(stops at shortest; use itertools.zip_longest for full)
Map & Filter:list(map(fn, iterable))list(filter(fn, iterable))
(returns lazy iterators; wrap in list() to materialise)
Sorted:sorted(iterable, key=fn, reverse=False)
(returns new list; list.sort() sorts in-place and returns None)
Any & All:any(iterable) / all(iterable)
(short-circuit: any stops at first True, all stops at first False)
Len, Min, Max, Sum:len(x) / min(x) / max(x) / sum(x)
(min/max accept a key= kwarg, same as sorted)
Strings are immutable sequences of Unicode characters. All
methods return new strings โ nothing mutates in place. f-strings
(Python 3.6+) are the preferred way to format: faster than
% formatting and more readable than
.format().
f-string (format):f"Hello {name!r:.10}"
(!r = repr, !s = str, !a = ascii; :.10 = max 10 chars)
Split & Join:"a,b,c".split(",")",".join(["a", "b", "c"])
(join is the inverse of split; separator goes on the joining string)
Strip:s.strip() / s.lstrip() / s.rstrip()
(removes whitespace by default; pass chars to strip those instead)
Replace:s.replace("old", "new", count=-1)
(optional count limits how many replacements are made)
Starts/Ends With:s.startswith("prefix") / s.endswith("suffix")
(also accept a tuple of strings to test multiple options)
Upper / Lower / Title:s.upper() / s.lower() / s.title()
(title capitalises the first letter of every word)
Python's core data structures. Lists are ordered and mutable,
dicts map keys to values (insertion-ordered since 3.7), and sets
store unique elements with O(1) membership testing. Comprehensions
are idiomatic and often faster than equivalent loops. The
collections module provides specialised variants for
common patterns.
List Comprehension:[x*2 for x in range(10) if x % 2 == 0]
(filter clause is optional; can be nested for multiple iterables)
Dict Comprehension:{k: v for k, v in items.items() if v}
(useful for transforming or filtering an existing dict)
List โ Append / Extend / Pop:lst.append(x) / lst.extend(iterable) / lst.pop(index)
(pop() without index removes the last item; O(n) for arbitrary index)
Dict โ Get with default:d.get("key", default)
(returns default instead of raising KeyError when key is absent)
Dict โ setdefault / update:d.setdefault("key", []) / d.update(other)
(setdefault inserts only if key is missing; update merges another dict in)
Dict โ Merge (Python 3.9+):merged = d1 | d2
(d2 values win on key conflicts; |= updates in place)
Set Operations:a | b (union) / a & b (intersection) / a - b (difference)
(all return new sets; use in-place versions |=, &=, -= to mutate)
from collections import defaultdict
d = defaultdict(list)
d["key"].append(1) # no KeyError on first access
(auto-creates missing keys using the factory; avoids KeyError on first access)
from collections import Counter
c = Counter("hello")
c.most_common(3) # [('l', 2), ('h', 1), ('e', 1)]
(subclass of dict; supports arithmetic between counters)
Python supports single and multiple inheritance with duck typing
โ if it has the right methods, it works. @dataclass
removes boilerplate for simple data containers and is the modern
replacement for writing __init__ by hand. Dunder
(double-underscore) methods let you define how objects behave with
operators and built-in functions.
from dataclasses import dataclass, field
@dataclass
class Point:
x: float
y: float = 0.0
tags: list = field(default_factory=list)
(auto-generates __init__, __repr__, __eq__; add frozen=True for immutability)
__str__ vs __repr__:__str__ = human-readable output (used by print)__repr__ = unambiguous representation (used in REPL/debug)
(if only one is defined, __repr__ is used as fallback for both)
Property:@property / @name.setter
(access like an attribute but backed by getter/setter methods; add validation in the setter)
Classmethod vs Staticmethod:@classmethod receives cls as first arg โ useful for alternative constructors@staticmethod receives no implicit arg โ just a namespaced function
Exceptions propagate up the call stack until caught. Always catch
specific exception types โ bare except: silences
every error including KeyboardInterrupt. Context
managers (with) guarantee cleanup code runs even if
an exception is raised, making them the idiomatic way to manage
resources like files and locks.
try:
result = risky()
except (TypeError, ValueError) as e:
print(f"caught: {e}")
else:
print("no exception") # runs only if no exception
finally:
cleanup() # always runs
Raise:raise ValueError("message")raise
(bare raise re-raises the current exception preserving the original traceback)
Context Manager:with open("file.txt") as f:
(calls __enter__ on entry and __exit__ on exit, even after exceptions)
Idiomatic Python ("Pythonic") code favours readability and
conciseness. Comprehensions, generators, and unpacking are core
tools. Type hints (Python 3.5+) improve editor support and catch
bugs early without being enforced at runtime โ use
mypy or pyright to check them.
Walrus Operator (Python 3.8+):if n := len(data):
(assign and test in one expression; useful in while loops and comprehensions)
Unpacking:a, *rest, b = [1, 2, 3, 4, 5]
(* collects the middle elements; works in function args too)
Lambda:fn = lambda x, y: x + y
(single-expression anonymous function; prefer def for anything more complex)
Generator Expression:total = sum(x*x for x in range(100))
(lazy โ produces values one at a time without building a list in memory)
def greet(name: str) -> str:
return f"Hello {name}"
# Python 3.10+: use X | Y instead of Union[X, Y]
def parse(val: str | None) -> int | None:
return int(val) if val else None
(use mypy or pyright to enforce; not checked at runtime)