โ† Back to Cheat Sheets

๐Ÿ Python Cheat Sheet

Complete Python reference โ€” data structures, OOP, comprehensions, decorators, itertools, regex, and more.

Data Structures

List Operations
nums = [1, 2, 3, 4, 5]
nums.append(6)           # Add to end
nums.insert(0, 0)        # Insert at index
nums.pop()               # Remove & return last
nums.remove(3)           # Remove first occurrence
nums.extend([7, 8])      # Add multiple
nums.sort(reverse=True)  # Sort in-place
sorted_new = sorted(nums) # Returns new list
nums.reverse()           # Reverse in-place
nums.index(2)            # Find index of value
sliced = nums[1:4]       # Slice [start:end)
nums[::2]                # Every 2nd element
nums[::-1]               # Reversed copy
Complete list methods โ€” mutable ordered sequences.
Dictionary
d = {'name': 'Alice', 'age': 30}
d['city'] = 'NYC'              # Add/update key
d.get('missing', 'default')    # Safe access
d.setdefault('role', 'eng')    # Set if missing
d.pop('age')                   # Remove & return
d.update({'age': 31, 'x': 1})  # Merge dict
d.keys()   # dict_keys
d.values() # dict_values
d.items()  # Key-value pairs

# Dict comprehension
{k: v**2 for k, v in d.items() if isinstance(v, int)}

# Merge dicts (3.9+)
merged = d1 | d2
Key-value mappings with O(1) lookups.
Set
s = {1, 2, 3}
s.add(4)              # Add element
s.discard(2)          # Remove (no error if missing)
s.remove(3)           # Remove (raises KeyError)

a | b    # Union
a & b    # Intersection
a - b    # Difference
a ^ b    # Symmetric difference
a <= b   # Subset check

# Frozen set (immutable, hashable)
fs = frozenset([1, 2, 3])
Unordered unique elements with set operations.
Tuple & Named Tuple
t = (1, 'hello', 3.14)    # Immutable
a, b, c = t               # Unpack
first, *rest = [1,2,3,4]  # first=1, rest=[2,3,4]
_, val, _ = (1, 2, 3)     # Ignore with _

# Named tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y)  # Attribute access
Immutable sequences and self-documenting tuples.
Collections Module
from collections import defaultdict, Counter, deque, OrderedDict

# defaultdict: auto-creates missing keys
dd = defaultdict(list)
dd['fruits'].append('apple')

# Counter: count elements
c = Counter(['a','b','a','c','a'])
c.most_common(2)  # [('a', 3), ('b', 1)]

# deque: efficient append/pop from both ends
dq = deque([1,2,3], maxlen=5)
dq.appendleft(0)
dq.rotate(1)  # Shift right
Specialized containers for common patterns.

Comprehensions & Generators

List Comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
flat = [x for row in matrix for x in row]
pairs = [(x,y) for x in range(3) for y in range(3) if x != y]
Concise list creation with filtering and nesting.
Dict & Set Comprehension
# Dict comprehension
word_len = {w: len(w) for w in words}
inverted = {v: k for k, v in original.items()}

# Set comprehension
unique_lengths = {len(w) for w in words}
Build dicts and sets with comprehension syntax.
Generator Functions
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)

# Generator expression (lazy, memory efficient)
gen = (x**2 for x in range(1_000_000))
next(gen)  # Produces values one at a time
Lazy iterators that yield values on demand.

Functions & Decorators

Args & Kwargs
def func(a, b, *args, **kwargs):
    print(a, b)       # Positional
    print(args)        # Extra positional as tuple
    print(kwargs)      # Extra keyword as dict

func(1, 2, 3, 4, key='val')

# Unpack into function call
args = [1, 2, 3]
kwargs = {'end': '\n'}
print(*args, **kwargs)
Flexible function signatures with packing/unpacking.
Lambda & Functional
double = lambda x: x * 2
list(map(str.upper, ['a', 'b', 'c']))
list(filter(lambda x: x > 0, [-1, 2, -3, 4]))

from functools import reduce
product = reduce(lambda a, b: a * b, [1,2,3,4])  # 24

# Partial application
from functools import partial
add_10 = partial(lambda a, b: a + b, 10)
add_10(5)  # 15
Functional programming โ€” lambda, map, filter, reduce, partial.
Decorators
import functools, time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f'{func.__name__} took {time.time()-start:.2f}s')
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)

# Decorator with arguments
def retry(attempts=3):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for i in range(attempts):
                try: return func(*args, **kwargs)
                except Exception: pass
        return wrapper
    return decorator
Wrap functions to add behavior โ€” timing, retries, caching.
Built-in Decorators
@staticmethod    # No self, no cls
@classmethod     # Gets cls instead of self
@property        # Getter as attribute
@functools.lru_cache(maxsize=128)  # Memoization
@functools.cached_property  # One-time computation (3.8+)
Essential built-in decorators for classes and caching.

OOP โ€” Classes

Class Basics
class Employee:
    company = 'Acme'  # Class variable

    def __init__(self, name: str, salary: float):
        self.name = name          # Instance variable
        self._salary = salary     # Convention: private

    @property
    def salary(self):
        return self._salary

    @salary.setter
    def salary(self, value):
        if value < 0: raise ValueError
        self._salary = value

    def __repr__(self):
        return f'Employee({self.name!r}, {self._salary})'
Classes with properties, encapsulation, and repr.
Inheritance & Dunder
class Manager(Employee):
    def __init__(self, name, salary, reports):
        super().__init__(name, salary)
        self.reports = reports

# Useful dunder methods:
__str__     # str(obj) / print(obj)
__repr__    # repr(obj) / debugging
__len__     # len(obj)
__getitem__ # obj[key]
__iter__    # for x in obj
__eq__      # obj1 == obj2
__lt__      # obj1 < obj2 (enables sorting)
__enter__/__exit__  # Context manager
Inheritance, super(), and magic methods.
Dataclasses
from dataclasses import dataclass, field

@dataclass
class Point:
    x: float
    y: float
    label: str = 'origin'
    tags: list = field(default_factory=list)

    def distance(self) -> float:
        return (self.x**2 + self.y**2) ** 0.5

p = Point(3, 4)
print(p)  # Point(x=3, y=4, label='origin', tags=[])
Auto-generated __init__, __repr__, __eq__ for data classes.

String Operations

String Methods
s = '  Hello, World!  '
s.strip()             # 'Hello, World!'
s.lstrip()            # 'Hello, World!  '
s.split(', ')         # ['Hello', 'World!']
'-'.join(['a','b'])   # 'a-b'
s.replace('World', 'Python')
s.startswith('Hello') # True (after strip)
s.endswith('!')
s.find('World')       # Index or -1
s.count('l')          # 3
s.isdigit()           # False
s.zfill(20)           # Zero-pad
Complete string method reference.
F-Strings & Formatting
name, score = 'Alice', 95.678
f'{name} scored {score:.1f}'   # 'Alice scored 95.7'
f'{score:>10.2f}'              # Right-align, 2 decimals
f'{1_000_000:,}'               # '1,000,000'
f'{0.156:.1%}'                 # '15.6%'
f'{name!r}'                    # "'Alice'" (repr)
f'{name:^20}'                  # Center in 20 chars

# Multi-line
query = f"""
  SELECT * FROM users
  WHERE name = '{name}'
"""
F-string formatting for numbers, alignment, and padding.
Regex
import re

re.search(r'\d+', 'abc123')       # Match object
re.findall(r'\d+', 'a1 b22 c3')  # ['1','22','3']
re.sub(r'\s+', ' ', text)         # Replace whitespace
re.split(r'[,;]', 'a,b;c')       # ['a','b','c']

# Groups
m = re.match(r'(\w+)@(\w+)', 'user@domain')
m.group(1)  # 'user'
m.group(2)  # 'domain'

# Common patterns
r'\d+'     # Digits
r'\w+'     # Word chars
r'[A-Z]'   # Uppercase
r'^...$'   # Full match
r'(?i)'    # Case insensitive flag
Regular expressions โ€” search, extract, replace.

Itertools & Built-ins

Essential Built-ins
sorted(data, key=lambda x: x['age'], reverse=True)
list(enumerate(['a','b','c'], start=1)) # [(1,'a'),...]
list(zip(names, scores))        # Pair elements
dict(zip(keys, values))         # Build dict from pairs

any([False, True, False])  # True (at least one)
all([True, True, False])   # False (not all)
min(data, key=len)         # Min by custom key
max(data, key=lambda x: x['score'])
sum(nums, start=0)

isinstance(obj, (int, float))  # Type check
hasattr(obj, 'method_name')    # Attribute check
Built-in functions for everyday data processing.
Itertools
from itertools import (
    chain, islice, groupby, product,
    combinations, permutations, accumulate, count
)

# chain: flatten iterables
list(chain([1,2], [3,4]))       # [1,2,3,4]

# groupby: group consecutive equal elements
for key, group in groupby(sorted(data), key=func):
    print(key, list(group))

# combinations & permutations
list(combinations('ABC', 2))  # [('A','B'),('A','C'),('B','C')]
list(permutations('AB', 2))   # [('A','B'),('B','A')]

# product: Cartesian product
list(product([1,2], ['a','b'])) # [(1,'a'),(1,'b'),(2,'a'),(2,'b')]

# accumulate: running totals
list(accumulate([1,2,3,4]))  # [1,3,6,10]
Efficient looping utilities from itertools.

File I/O & Error Handling

File Read/Write
# Read entire file
with open('data.txt', 'r', encoding='utf-8') as f:
    content = f.read()

# Read line by line (memory efficient)
with open('big_file.txt') as f:
    for line in f:
        process(line.strip())

# Write
with open('out.csv', 'w') as f:
    f.write('col1,col2\n')

# Append
with open('log.txt', 'a') as f:
    f.write('new entry\n')

# JSON
import json
with open('data.json') as f:
    data = json.load(f)
with open('out.json', 'w') as f:
    json.dump(data, f, indent=2)
Read, write, append files with context managers.
CSV & Path
import csv
from pathlib import Path

# CSV reading
with open('data.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['name'], row['age'])

# pathlib (modern file paths)
p = Path('data') / 'output' / 'file.txt'
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text('hello')
p.read_text()
p.exists()
p.suffix    # '.txt'
p.stem      # 'file'
list(Path('.').glob('**/*.py'))  # Recursive glob
CSV processing and modern path handling.
Error Handling
try:
    result = risky_operation()
except FileNotFoundError:
    print('File missing')
except (ValueError, TypeError) as e:
    print(f'Bad input: {e}')
except Exception as e:
    logger.error(f'Unexpected: {e}')
    raise  # Re-raise after logging
else:
    print('Success!')  # Runs if no exception
finally:
    cleanup()          # Always runs

# Custom exceptions
class DataPipelineError(Exception):
    def __init__(self, stage, message):
        self.stage = stage
        super().__init__(f'[{stage}] {message}')
Complete error handling with custom exceptions.

Type Hints & Context Managers

Type Hints
from typing import (
    Optional, Union, Any, Callable,
    TypeVar, Generic
)

def greet(name: str) -> str:
    return f'Hello, {name}'

def process(data: list[dict[str, Any]]) -> Optional[int]:
    ...

# Union types (3.10+)
def parse(val: int | str) -> float: ...

# Callable
def apply(func: Callable[[int], int], x: int) -> int:
    return func(x)

# TypeVar for generics
T = TypeVar('T')
def first(items: list[T]) -> T:
    return items[0]
Type annotations for functions and variables.
Context Managers
from contextlib import contextmanager

@contextmanager
def timer(label):
    import time
    start = time.time()
    try:
        yield
    finally:
        elapsed = time.time() - start
        print(f'{label}: {elapsed:.2f}s')

with timer('data load'):
    load_data()

# Class-based context manager
class DBConnection:
    def __enter__(self):
        self.conn = connect()
        return self.conn
    def __exit__(self, exc_type, exc_val, tb):
        self.conn.close()
        return False  # Don't suppress exceptions
Custom context managers for resource management.