Python Cheatsheet

A comprehensive quick reference for Python syntax, data structures, and the most commonly used standard library modules. From beginners to experienced developers, everything you need on one page.

Data Types

TypeDescription
intArbitrary-precision integer: 42, -7, 0xff, 0b1010, 1_000_000
float64-bit floating point: 3.14, 2.5e-3, float('inf'), float('nan')
complexComplex number: 3+4j, complex(3, 4)
boolBoolean: True, False (subclass of int)
strImmutable Unicode text: 'hello', "world", '''multi-line'''
bytesImmutable byte sequence: b'hello', bytes([72, 101])
bytearrayMutable byte sequence: bytearray(b'hello')
listOrdered, mutable sequence: [1, 2, 3]
tupleOrdered, immutable sequence: (1, 2, 3) or 1, 2, 3
setUnordered unique elements: {1, 2, 3}
frozensetImmutable set: frozenset({1, 2, 3})
dictKey-value mapping: {'a': 1, 'b': 2}
NoneSingleton null value
rangeImmutable sequence of numbers: range(10), range(1, 10, 2)

Type Conversion

CodeDescription
int(x)Convert to integer (truncates float, parses string)
float(x)Convert to float
str(x)Convert to string representation
bool(x)Convert to boolean (falsy: 0, '', None, [], {}, set())
list(x)Convert iterable to list
tuple(x)Convert iterable to tuple
set(x)Convert iterable to set (deduplicates)
dict(pairs)Convert iterable of (key, value) pairs to dict
chr(n)Integer to Unicode character: chr(65) -> 'A'
ord(c)Character to Unicode code point: ord('A') -> 65
hex(n) / oct(n) / bin(n)Integer to hex/octal/binary string

Control Flow & Functions

Control Flow

SyntaxDescription
if / elif / elseConditional branching
for x in iterable:Iterate over elements
for i, x in enumerate(lst):Iterate with index
for k, v in d.items():Iterate dict key-value pairs
while condition:Loop while condition is true
break / continue / passLoop control / no-op statement
for ... else:else block runs if loop completes without break
match value: case pattern:Structural pattern matching (Python 3.10+)
x if cond else yTernary conditional expression

Functions

SyntaxDescription
def func(a, b=10):Function with positional and default args
def func(*args, **kwargs):Variadic positional and keyword args
def func(a, /, b, *, c):Positional-only (/) and keyword-only (*) args
lambda x, y: x + yAnonymous function expression
def func() -> int:Return type annotation
def func(x: str) -> None:Parameter and return annotations
return valueReturn a value (None if omitted)
yield valueGenerator function (lazy iteration)
yield from iterableDelegate to sub-generator
async def func():Async coroutine function
await coroutineAwait an async operation
global var / nonlocal varAccess outer scope variables

Built-in Functions

CodeDescription
print(*args, sep, end, file)Print to stdout
input(prompt)Read line from stdin
len(x) / type(x) / id(x)Length, type, identity
isinstance(obj, T) / issubclass(C, T)Type checking
range(stop) / range(start, stop, step)Integer sequence
enumerate(it, start=0)Index-element pairs
zip(*iterables)Combine iterables element-wise
map(fn, it) / filter(fn, it)Apply / filter by function
any(it) / all(it)True if any/all elements truthy
min(it) / max(it) / sum(it)Aggregate functions
sorted(it, key, reverse)Return sorted list
reversed(seq)Reverse iterator
abs(x) / round(x, n)Absolute value / round
divmod(a, b)Return (quotient, remainder)
pow(base, exp, mod)Exponentiation (with optional modulo)
hash(obj)Hash value
callable(obj)Check if object is callable
dir(obj)List attributes and methods
vars(obj)Object's __dict__
getattr(obj, name, default)Get attribute by name
setattr(obj, name, value)Set attribute by name
hasattr(obj, name)Check if attribute exists
repr(obj) / str(obj)String representations
eval(expr) / exec(code)Execute string as code (use carefully!)
open(path, mode)Open file
iter(obj) / next(it, default)Create iterator / get next element

String Methods

Strings in Python are immutable. All methods return a new string.

MethodDescription
s.upper() / s.lower()Convert to uppercase / lowercase
s.capitalize()Capitalize first character
s.title()Title Case Each Word
s.strip() / lstrip() / rstrip()Remove whitespace (or given chars) from ends
s.split(sep, maxsplit)Split into list by separator (default: whitespace)
s.rsplit(sep, maxsplit)Split from the right
s.splitlines()Split by line breaks
'sep'.join(iterable)Join iterable of strings with separator
s.replace(old, new, count)Replace occurrences of substring
s.find(sub) / s.rfind(sub)Find index of substring (-1 if not found)
s.index(sub) / s.rindex(sub)Like find but raises ValueError if not found
s.count(sub)Count non-overlapping occurrences
s.startswith(prefix)Check if string starts with prefix (tuple of prefixes OK)
s.endswith(suffix)Check if string ends with suffix
s.isdigit() / s.isalpha() / s.isalnum()Character type checks
s.isupper() / s.islower() / s.isspace()Case and whitespace checks
s.zfill(width)Pad with zeros on the left
s.ljust(w) / s.rjust(w) / s.center(w)Pad/align string to width
s.encode(encoding)Encode to bytes (default: utf-8)
s.format(*args, **kwargs)Format string: '{} {}'.format('a', 'b')
f'{expr}'f-string (Python 3.6+): f'{name!r} is {age}'
s.maketrans() / s.translate()Create and apply character translation table
s.removeprefix(p) / s.removesuffix(s)Remove prefix/suffix if present (Python 3.9+)

List Operations

OperationDescription
lst[i]Access by index (0-based, negative from end)
lst[start:stop:step]Slice: lst[1:5], lst[::2], lst[::-1] (reverse)
lst.append(x)Add element to the end
lst.extend(iterable)Append all elements from iterable
lst.insert(i, x)Insert element at index i
lst.remove(x)Remove first occurrence of x (ValueError if missing)
lst.pop(i=-1)Remove and return element at index (default: last)
lst.clear()Remove all elements
lst.index(x, start, end)Find index of first occurrence
lst.count(x)Count occurrences of x
lst.sort(key=None, reverse=False)Sort in place
sorted(lst, key, reverse)Return new sorted list
lst.reverse()Reverse in place
lst.copy()Shallow copy
len(lst)Number of elements
x in lstMembership test
lst + lst2Concatenate lists
lst * nRepeat list n times
min(lst) / max(lst) / sum(lst)Aggregate functions
list(zip(a, b))Pair elements from two iterables
list(enumerate(lst))Pairs of (index, element)
list(map(fn, lst))Apply function to each element
list(filter(fn, lst))Keep elements where fn returns True

Dict Operations

OperationDescription
d[key]Get value (KeyError if missing)
d.get(key, default)Get value or return default (None if omitted)
d[key] = valueSet value for key
d.setdefault(key, default)Get value; if missing, insert default and return it
d.update(other)Merge another dict (or key-value pairs) into d
d | otherMerge dicts, returning new dict (Python 3.9+)
d |= otherMerge in place (Python 3.9+)
del d[key]Delete key (KeyError if missing)
d.pop(key, default)Remove and return value (or default)
d.popitem()Remove and return last inserted (key, value) pair
d.clear()Remove all items
d.keys()View of all keys
d.values()View of all values
d.items()View of (key, value) pairs
key in dCheck if key exists
len(d)Number of key-value pairs
dict(zip(keys, values))Create dict from two iterables
dict.fromkeys(keys, value)Create dict with given keys and same value
d.copy()Shallow copy

Set Operations

OperationDescription
s.add(x)Add element to set
s.discard(x)Remove element if present (no error if missing)
s.remove(x)Remove element (KeyError if missing)
s.pop()Remove and return an arbitrary element
s.clear()Remove all elements
s | t or s.union(t)Union: elements in s or t
s & t or s.intersection(t)Intersection: elements in both s and t
s - t or s.difference(t)Difference: elements in s but not t
s ^ t or s.symmetric_difference(t)Symmetric difference: in s or t but not both
s <= t or s.issubset(t)Is s a subset of t?
s >= t or s.issuperset(t)Is s a superset of t?
s.isdisjoint(t)True if no common elements
len(s)Number of elements
x in sMembership test (O(1) average)
s.copy()Shallow copy

Comprehensions

SyntaxDescription
[x for x in iterable]List comprehension
[x for x in iterable if cond]Filtered list comprehension
[f(x) for x in iterable]Mapped list comprehension
[x for sub in nested for x in sub]Flatten nested iterables
{k: v for k, v in items}Dict comprehension
{x for x in iterable}Set comprehension
(x for x in iterable)Generator expression (lazy, memory-efficient)
[x if cond else y for x in it]Conditional expression in comprehension

File I/O

CodeDescription
open(path, mode, encoding)Open file. Modes: 'r' read, 'w' write, 'a' append, 'x' exclusive create, 'b' binary
with open(path) as f:Context manager (auto-closes file)
f.read()Read entire file as string
f.read(n)Read n characters
f.readline()Read one line
f.readlines()Read all lines as list
for line in f:Iterate lines (memory-efficient)
f.write(string)Write string to file
f.writelines(lines)Write list of strings (no newlines added)
f.seek(offset, whence)Move file cursor (0=start, 1=current, 2=end)
f.tell()Current cursor position
f.flush()Flush write buffer
f.close()Close file (prefer with statement)
Path(p).read_text()pathlib one-liner for reading text
Path(p).write_text(s)pathlib one-liner for writing text
Path(p).read_bytes()pathlib one-liner for reading bytes

Error Handling

Syntax

SyntaxDescription
try: ... except: ...Catch any exception
except ExType as e:Catch specific exception type
except (T1, T2) as e:Catch multiple exception types
else:Block runs if no exception was raised
finally:Block always runs (cleanup)
raise ExType(msg)Raise an exception
raise ... from causeChain exceptions (explicit cause)
assert condition, msgAssertion (raises AssertionError)
class MyError(Exception): passDefine a custom exception
with contextlib.suppress(T):Silently ignore specific exceptions

Common Exceptions

ExceptionDescription
ValueErrorWrong value (e.g., int('abc'))
TypeErrorWrong type (e.g., '1' + 2)
KeyErrorMissing dict key
IndexErrorIndex out of range
AttributeErrorMissing attribute/method
NameErrorUndefined variable
FileNotFoundErrorFile or directory not found
IOError / OSErrorOS-level I/O error
ImportError / ModuleNotFoundErrorFailed import
ZeroDivisionErrorDivision by zero
StopIterationIterator exhausted
RuntimeErrorGeneric runtime error
NotImplementedErrorAbstract method not implemented
RecursionErrorMaximum recursion depth exceeded

Classes & OOP

FeatureDescription
class MyClass:Define a class
class Child(Parent):Single inheritance
class C(A, B):Multiple inheritance (MRO: C3 linearization)
def __init__(self, ...):Constructor (initializer)
def __repr__(self):Developer-friendly string representation
def __str__(self):User-friendly string (used by print)
def __len__(self):Support len(obj)
def __getitem__(self, key):Support obj[key]
def __setitem__(self, key, val):Support obj[key] = val
def __iter__(self):Make object iterable
def __contains__(self, item):Support 'in' operator
def __eq__(self, other):Equality comparison (==)
def __lt__(self, other):Less-than comparison (<)
def __hash__(self):Make object hashable (for sets/dicts)
def __call__(self, ...):Make object callable like a function
def __enter__ / __exit__:Context manager protocol (with statement)
@propertyGetter for computed attribute
@name.setterSetter for property
@staticmethodMethod that doesn't receive self or cls
@classmethodMethod that receives cls instead of self
super()Access parent class methods
@dataclasses.dataclassAuto-generate __init__, __repr__, __eq__ (Python 3.7+)
slots = ['x', 'y']Restrict attributes for memory savings (__slots__)

Decorators

SyntaxDescription
@decorator\ndef func(): ...Apply decorator to function (func = decorator(func))
@decorator(args)\ndef func(): ...Decorator factory: decorator(args) returns the actual decorator
@functools.wraps(fn)Preserve original function metadata in wrapper
@functools.lru_cache(maxsize)Memoize function results
@functools.cacheUnbounded memoization cache (Python 3.9+)
@staticmethodStatic method (no self/cls)
@classmethodClass method (receives cls)
@propertyDefine a getter property
@abstractmethodMark method as abstract (from abc.ABC)
@contextmanagerCreate context manager from generator (contextlib)
@dataclassAuto-generate class boilerplate
@overloadType hint overloads (typing)

os & pathlib

os Module

CodeDescription
os.getcwd()Current working directory
os.listdir(path)List directory contents
os.makedirs(path, exist_ok=True)Create directories recursively
os.remove(path) / os.unlink(path)Delete a file
os.rmdir(path)Remove empty directory
os.rename(src, dst)Rename/move file or directory
os.path.exists(path)Check if path exists
os.path.join(a, b)Join path components
os.path.basename(path)File name from path
os.path.dirname(path)Directory from path
os.path.splitext(path)Split into (root, ext)
os.path.getsize(path)File size in bytes
os.path.isfile(p) / isdir(p)Check if file or directory
os.environ['KEY']Access environment variable
os.environ.get('KEY', default)Environment variable with default
os.system(cmd)Run shell command (prefer subprocess)

pathlib.Path

CodeDescription
Path('dir/file.txt')Create a Path object
p / 'sub' / 'file'Join paths with / operator
p.name / p.stem / p.suffixfile.txt / file / .txt
p.parentParent directory
p.exists() / p.is_file() / p.is_dir()Existence and type checks
p.mkdir(parents=True, exist_ok=True)Create directories
p.glob('*.py') / p.rglob('*.py')Glob / recursive glob
p.resolve()Absolute path
p.rename(target) / p.unlink()Rename / delete
p.stat().st_sizeFile size
p.iterdir()Iterate directory contents

json

CodeDescription
json.dumps(obj)Serialize to JSON string
json.dumps(obj, indent=2)Pretty-print JSON
json.loads(string)Parse JSON string to Python object
json.dump(obj, file)Write JSON to file
json.load(file)Read JSON from file
json.dumps(obj, default=str)Handle non-serializable types
json.dumps(obj, ensure_ascii=False)Allow non-ASCII characters
json.dumps(obj, sort_keys=True)Sort dictionary keys

re (Regular Expressions)

CodeDescription
re.search(pattern, string)Find first match anywhere in string
re.match(pattern, string)Match at beginning of string only
re.fullmatch(pattern, string)Match entire string
re.findall(pattern, string)List of all non-overlapping matches
re.finditer(pattern, string)Iterator of match objects
re.sub(pattern, repl, string)Replace matches
re.split(pattern, string)Split by pattern
re.compile(pattern)Pre-compile for repeated use
m.group(0) / m.group(1)Full match / first capture group
m.groups()Tuple of all capture groups
m.start() / m.end() / m.span()Match position
re.IGNORECASE / re.MULTILINE / re.DOTALLCommon flags (re.I, re.M, re.S)

datetime

CodeDescription
datetime.now()Current local date and time
datetime.utcnow()Current UTC date and time (naive)
datetime.now(timezone.utc)Current UTC date and time (aware)
datetime(2025, 1, 15, 10, 30)Create specific datetime
date.today()Current local date
dt.strftime('%Y-%m-%d %H:%M:%S')Format datetime to string
datetime.strptime(s, fmt)Parse string to datetime
dt.timestamp()Convert to Unix timestamp
datetime.fromtimestamp(ts)Create from Unix timestamp
dt.date() / dt.time()Extract date or time part
dt.replace(year=2026)Return copy with replaced fields
dt.isoformat()ISO 8601 string
datetime.fromisoformat(s)Parse ISO 8601 string (Python 3.7+)
timedelta(days=7, hours=2)Represent a duration
dt + timedelta(days=30)Date arithmetic
(dt2 - dt1).total_seconds()Difference in seconds

collections

CodeDescription
Counter(iterable)Count element occurrences: Counter('abracadabra')
c.most_common(n)n most common elements with counts
defaultdict(factory)Dict with default value factory: defaultdict(list)
OrderedDict()Dict that remembers insertion order (less needed in 3.7+)
deque(iterable, maxlen)Double-ended queue with O(1) append/pop both ends
dq.appendleft(x) / dq.popleft()Deque left-side operations
dq.rotate(n)Rotate deque n steps (positive = right)
namedtuple('Point', ['x', 'y'])Create lightweight immutable class
ChainMap(d1, d2, ...)Logical merge of multiple dicts (first match wins)

itertools

CodeDescription
count(start, step)Infinite counter: 10, 11, 12, ...
cycle(iterable)Infinite cycle: A, B, C, A, B, C, ...
repeat(elem, n)Repeat element n times (or infinitely)
chain(it1, it2)Chain iterables: [1,2] + [3,4] -> 1,2,3,4
chain.from_iterable(its)Flatten one level of nesting
islice(it, start, stop, step)Slice an iterator (lazy)
zip_longest(*its, fillvalue)Zip with fill for shorter iterables
product(A, B)Cartesian product: all (a, b) pairs
permutations(it, r)All r-length permutations
combinations(it, r)All r-length combinations (no repeats)
combinations_with_replacement(it, r)Combinations with repeats allowed
groupby(it, key)Group consecutive elements by key (sort first!)
accumulate(it, func)Running totals: [1,2,3] -> [1,3,6]
starmap(func, it)Apply func(*args) for each args tuple
takewhile(pred, it) / dropwhile(pred, it)Take/drop while predicate is true
filterfalse(pred, it)Keep elements where predicate is false
tee(it, n)Create n independent iterators from one
pairwise(it)Sliding pairs: [1,2,3] -> (1,2),(2,3) (Python 3.10+)
batched(it, n)Group into tuples of n (Python 3.12+)

Related Resources