Python Cheat Sheet
Every Python built-in, syntax pattern and idiom, searchable and copy-ready.
By Bogdan SanduUpdated August 2, 2026
Highlight Python code
The result appears here.
Basics
Quick reference
| Task | Command |
|---|---|
| Print to console | print('Hello, World!') |
| Assign variables | x = 10; name = 'Alice' |
| Check type | type(x) |
| Comment | # This is a comment |
Variables & Types
Basic variable assignment
42 # int
3.14 # float
'hello' # str
True # bool
None # NoneTypeMultiple assignment
a, b, c = 1, 2, 3
x = y = z = 0
first, *rest = [1, 2, 3, 4] # rest = [2, 3, 4]Type checking and conversion
type(x) # <class 'int'>
isinstance(x, int) # True
int('42') # 42
float(3) # 3.0
str(100) # '100'
bool(0) # FalseArithmetic operators
10 + 3 # 13 addition
10 - 3 # 7 subtraction
10 * 3 # 30 multiplication
10 / 3 # 3.333... true division
10 // 3 # 3 floor division
10 % 3 # 1 modulo
2 ** 8 # 256 exponentiationComparison and logical operators
x == y # equal
x != y # not equal
x > y # greater than
x < y # less than
x >= y # greater or equal
not x # logical NOT
x and y # logical AND
x or y # logical ORUser input
name = input('Enter name: ')
age = int(input('Enter age: '))Numbers
Math built-ins
abs(-5) # 5
round(3.14159, 2) # 3.14
min(3, 1, 4) # 1
max(3, 1, 4) # 4
sum([1, 2, 3]) # 6
pow(2, 10) # 1024math module essentials
import math
math.sqrt(16) # 4.0
math.ceil(4.2) # 5
math.floor(4.9) # 4
math.log(100, 10) # 2.0
math.pi # 3.14159…
math.inf # infinityInteger bases and binary operations
bin(42) # '0b101010'
hex(255) # '0xff'
oct(8) # '0o10'
0b1010 # 10
0xFF # 255Truthiness & Identity
Falsy values in Python
# All of these are falsy:
False, None, 0, 0.0, '', [], {}, set()
# Everything else is truthyIdentity vs equality
x is y # same object in memory
x is not y # different objects
x == y # same value
x is None # preferred None checkWalrus operator (Python 3.8+)
if n := len(data):
print(f'Got {n} items')
while chunk := file.read(1024):
process(chunk)Strings
Quick reference
| Task | Command |
|---|---|
| f-string | f'Hello, {name}!' |
| Split on delimiter | s.split(',') |
| Join list to string | ', '.join(items) |
| Clean a string | s.strip().lower() |
String Literals & Formatting
String literal types
'single'
"double"
"""triple
multiline"""
r'\n is literal backslash-n' # raw
b'bytes' # bytesf-strings (Python 3.6+)
name = 'Alice'
age = 30
print(f'{name} is {age}')
print(f'Pi = {3.14159:.2f}') # Pi = 3.14
print(f'{1000000:,}') # 1,000,000
print(f'{name!r}') # repr
print(f'{name:>10}') # right-alignString concatenation and repetition
'Hello' + ' World' # 'Hello World'
'-' * 20 # '--------------------'Common String Methods
Case methods
s.upper() # 'HELLO'
s.lower() # 'hello'
s.title() # 'Hello World'
s.capitalize() # 'Hello world'
s.swapcase() # invert caseSearch and check methods
s.find('sub') # index or -1
s.index('sub') # index or ValueError
s.count('l') # occurrences
s.startswith('H') # True/False
s.endswith('.py') # True/False
'x' in s # True/FalseTrim, replace, split, join
s.strip() # remove leading/trailing whitespace
s.lstrip('/') # strip left only
s.replace('a', 'b') # replace all occurrences
s.split(',') # list of parts
s.split(',', 2) # max 2 splits
', '.join(['a','b']) # 'a, b'Validation methods
s.isdigit() # all digits
s.isalpha() # all letters
s.isalnum() # letters or digits
s.isspace() # all whitespace
s.isupper() # all uppercasestr.format() - older style formatting
'{} is {}'.format('Alice', 30)
'{name} is {age}'.format(name='Alice', age=30)
'{0:.2f}'.format(3.14159) # '3.14'
'{:>10}'.format('hi') # ' hi'
'{:0>5d}'.format(42) # '00042'Slicing & Indexing
String slicing [start:stop:step]
s = 'Hello, World!'
s[0] # 'H'
s[-1] # '!'
s[0:5] # 'Hello'
s[7:] # 'World!'
s[:5] # 'Hello'
s[::-1] # '!dlroW ,olleH' (reverse)
s[::2] # every other charString padding and alignment
s.ljust(10) # 'hello '
s.rjust(10) # ' hello'
s.center(10) # ' hello '
s.zfill(8) # '000hello'
'42'.zfill(5) # '00042'Lists & Tuples
Quick reference
| Task | Command |
|---|---|
| Add to end | items.append(x) |
| Remove from end | items.pop() |
| Sort by key | sorted(items, key=...) |
| Filter a list | [x for x in items if ...] |
List Operations
Create and access lists
nums = [1, 2, 3, 4, 5]
nums[0] # 1 (first)
nums[-1] # 5 (last)
nums[1:3] # [2, 3]
len(nums) # 5Mutating a list
lst.append(x) # add to end
lst.insert(0, x) # insert at index
lst.extend([4, 5]) # add multiple
lst.remove(x) # remove first x
lst.pop() # remove & return last
lst.pop(0) # remove & return index 0
lst.clear() # empty the list
del lst[2] # delete by indexSorting
lst.sort() # in-place ascending
lst.sort(reverse=True) # in-place descending
sorted(lst) # returns new list
sorted(lst, key=len) # sort by length
sorted(lst, key=lambda x: x[1]) # sort by index 1Search and info
x in lst # membership test
lst.index(x) # first index of x
lst.count(x) # count occurrences
lst.reverse() # in-place reverse
lst[:] # shallow copy
lst.copy() # shallow copyList unpacking and spreading
a, b, *rest = [1, 2, 3, 4, 5]
# a=1, b=2, rest=[3,4,5]
combined = [*lst1, *lst2] # merge
lst + lst2 # concatenate
lst * 3 # repeatSorting with operator.itemgetter / attrgetter
from operator import itemgetter, attrgetter
rows = [{'name':'Bob','age':30},{'name':'Alice','age':25}]
sorted(rows, key=itemgetter('age'))
# Multi-key: age ASC, then name ASC
sorted(rows, key=lambda r: (r['age'], r['name']))
# Sort objects by attribute
sorted(people, key=attrgetter('last_name', 'age'))Tuples
Tuple basics - immutable sequences
t = (1, 2, 3)
t = 1, 2, 3 # parens optional
t = (42,) # single-element tuple (comma!)
x, y, z = t # unpack
t[0] # access (immutable)
t.count(1) # count occurrences
t.index(2) # find indexNamed tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
p.x # 1
p.y # 2Dicts & Sets
Quick reference
| Task | Command |
|---|---|
| Safe key access | d.get('key', default) |
| Iterate key-value pairs | d.items() |
| Merge dicts | {**d1, **d2} |
| Group into dict | d.setdefault('k', []).append(v) |
Dictionary Operations
Create and access dicts
d = {'name': 'Alice', 'age': 30}
d['name'] # 'Alice'
d.get('age') # 30
d.get('x', 0) # 0 (default, no KeyError)
'name' in d # TrueMutating dicts
d['city'] = 'NYC' # add/update
d.update({'x': 1}) # merge in
d.pop('age') # remove & return
d.pop('x', None) # safe remove
del d['city'] # delete key
d.clear() # empty dictIterating dicts
for key in d: # keys
print(key)
for k, v in d.items(): # key-value pairs
print(k, v)
d.keys() # dict_keys view
d.values() # dict_values viewMerging dicts
# Python 3.9+
merged = d1 | d2
# All versions
merged = {**d1, **d2}
# Update in place (3.9+)
d1 |= d2defaultdict and Counter
from collections import defaultdict, Counter
dd = defaultdict(list)
dd['k'].append(1) # no KeyError
c = Counter(['a', 'b', 'a', 'c', 'a'])
c.most_common(2) # [('a', 3), ('b', 1)]
c['a'] # 3
c + Counter('abc') # add countsdeque - fast append/pop from both ends
from collections import deque
q = deque([1, 2, 3], maxlen=5)
q.append(4) # add right
q.appendleft(0) # add left
q.pop() # remove right
q.popleft() # remove left - O(1)
q.rotate(1) # rotate elementsChainMap - search multiple dicts in order
from collections import ChainMap
defaults = {'color': 'red', 'size': 10}
overrides = {'color': 'blue'}
config = ChainMap(overrides, defaults)
config['color'] # 'blue' (overrides first)
config['size'] # 10 (falls back to defaults)Sets
Create and mutate sets
s = {1, 2, 3}
s = set([1, 2, 2, 3]) # {1, 2, 3}
s.add(4)
s.discard(10) # no error if missing
s.remove(3) # KeyError if missing
2 in s # O(1) lookupSet operations
a | b # union
a & b # intersection
a - b # difference (in a, not b)
a ^ b # symmetric difference
a <= b # a is subset of b
a >= b # a is superset of bDeduplicate a list using a set
unique = list(set(my_list))
# preserves order (Python 3.7+):
unique = list(dict.fromkeys(my_list))Control Flow
Quick reference
| Task | Command |
|---|---|
| Loop with index | enumerate(items) |
| Loop two lists | zip(list1, list2) |
| Range with step | range(0, 10, 2) |
| Ternary expression | x if cond else y |
if / elif / else
Basic conditionals
if x > 0:
print('positive')
elif x == 0:
print('zero')
else:
print('negative')Ternary (conditional expression)
label = 'even' if n % 2 == 0 else 'odd'
score = max(0, min(100, raw)) # clampmatch / case (Python 3.10+)
match command:
case 'quit':
quit()
case 'go' | 'run':
move()
case _:
print('unknown')for & while Loops
for loop patterns
for item in iterable:
print(item)
for i in range(5): # 0 to 4
print(i)
for i, v in enumerate(lst): # index + value
print(i, v)
for a, b in zip(l1, l2): # parallel
print(a, b)while loop
while condition:
do_something()
while True:
data = get_input()
if data == 'quit':
breakbreak, continue, else on loops
for n in nums:
if n == 0:
continue # skip
if n < 0:
break # exit loop
else:
print('no break') # runs if no breakrange() patterns
range(5) # 0, 1, 2, 3, 4
range(1, 6) # 1, 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8
range(10, 0, -1) # 10, 9, … 1
list(range(5)) # [0, 1, 2, 3, 4]Functions
Quick reference
| Task | Command |
|---|---|
| Define a function | def func(a, b=10, **kwargs) |
| Lambda | lambda x, y: x + y |
| Map over list | map(func, iterable) |
| Filter a list | filter(func, iterable) |
Defining Functions
Basic function definition
def greet(name):
"""Docstring describes the function."""
return f'Hello, {name}!'Default arguments and keyword arguments
def connect(host, port=8080, secure=False):
return host, port, secure
connect('example.com')
connect('example.com', secure=True)
connect('example.com', 443, True)*args and **kwargs
def func(*args, **kwargs):
print(args) # tuple of positional
print(kwargs) # dict of keyword
func(1, 2, x=3, y=4)
# args=(1, 2), kwargs={'x': 3, 'y': 4}
# Spread on call side:
func(*[1, 2], **{'x': 3})Type hints (Python 3.5+)
def add(a: int, b: int) -> int:
return a + b
def process(items: list[str]) -> dict[str, int]:
return {s: len(s) for s in items}Lambdas, map, filter, functools
Lambda expressions
square = lambda x: x ** 2
square(5) # 25
pairs = [(1, 'b'), (3, 'a'), (2, 'c')]
sorted(pairs, key=lambda p: p[1])
# [(3, 'a'), (1, 'b'), (2, 'c')]map and filter
nums = [1, 2, 3, 4, 5]
list(map(str, nums)) # ['1','2','3','4','5']
list(map(lambda x: x*2, nums)) # [2,4,6,8,10]
list(filter(lambda x: x>2, nums))# [3,4,5]functools - reduce, partial, lru_cache
from functools import reduce, partial, lru_cache
reduce(lambda a, b: a+b, [1,2,3]) # 6
add5 = partial(add, b=5)
add5(3) # 8
@lru_cache(maxsize=None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)Generators & yield
Generator function
def count_up(n):
i = 0
while i < n:
yield i
i += 1
for x in count_up(3):
print(x) # 0, 1, 2Generator expression
squares = (x**2 for x in range(10))
next(squares) # 0 (lazy evaluation)
sum(x**2 for x in range(100)) # memory efficientClasses & OOP
Quick reference
| Task | Command |
|---|---|
| Define a class | class Dog: def __init__ |
| Inherit a class | class Cat(Animal): |
| Property getter | @property |
| Static / class method | @staticmethod / @classmethod |
Class Basics
Defining a class
class Animal:
species = 'unknown' # class variable
def __init__(self, name, sound):
self.name = name # instance variable
self.sound = sound
def speak(self):
return f'{self.name} says {self.sound}'
def __repr__(self):
return f'Animal({self.name!r})'Inheritance and super()
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, 'woof')
self.breed = breed
def speak(self): # override
base = super().speak()
return f'{base}!'
isinstance(d, Dog) # True
isinstance(d, Animal) # True@property, @classmethod, @staticmethod
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
import math
return math.pi * self.radius ** 2
@classmethod
def from_diameter(cls, d):
return cls(d / 2)
@staticmethod
def is_valid(r):
return r > 0Dataclasses & Dunder Methods
@dataclass (Python 3.7+)
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
tags: list[str] = field(default_factory=list)
p = Product('Book', 9.99)
# __init__, __repr__, __eq__ auto-generatedCommon dunder methods
__init__ # constructor
__repr__ # repr(obj)
__str__ # str(obj) / print
__len__ # len(obj)
__eq__ # obj == other
__lt__ # obj < other (enables sort)
__add__ # obj + other
__getitem__ # obj[key]
__iter__ # for x in obj
__next__ # next(obj)
__enter__ # with obj as …
__exit__ # end of with block__slots__ - restrict attributes, save memory
class Point:
__slots__ = ('x', 'y') # no __dict__
def __init__(self, x, y):
self.x = x
self.y = y
# p.z = 1 → AttributeError
# Useful when creating millions of instancesAbstract base classes (ABC)
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self) -> float: ...
@abstractmethod
def perimeter(self) -> float: ...
class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): import math; return math.pi * self.r**2
def perimeter(self): import math; return 2 * math.pi * self.r
# Shape() → TypeError: Can't instantiate abstract classComprehensions
Quick reference
| Task | Command |
|---|---|
| List comprehension | [x**2 for x in range(10)] |
| Dict comprehension | {k: v for k, v in d.items()} |
| Set comprehension | {x for x in items} |
| Generator expression | (x**2 for x in range(10)) |
List, Dict & Set Comprehensions
List comprehension with condition
evens = [x for x in range(20) if x % 2 == 0]
squares = [x**2 for x in range(10)]
words = [w.lower() for w in text.split()]Dict comprehension
lengths = {w: len(w) for w in words}
inverted = {v: k for k, v in d.items()}
filtered = {k: v for k, v in d.items() if v > 0}Set comprehension
unique_lengths = {len(w) for w in words}
vowels = {c for c in text.lower() if c in 'aeiou'}Nested comprehension - flatten a matrix
matrix = [[1,2],[3,4],[5,6]]
flat = [n for row in matrix for n in row]
# [1, 2, 3, 4, 5, 6]Conditional expression inside comprehension
labels = ['even' if x%2==0 else 'odd'
for x in range(6)]
# ['even','odd','even','odd','even','odd']itertools
itertools essentials
import itertools as it
it.chain([1,2], [3,4]) # flatten iterables
it.chain.from_iterable(matrix) # flatten nested
it.product([1,2], ['a','b']) # cartesian product
it.permutations([1,2,3], 2) # ordered combos
it.combinations([1,2,3], 2) # unordered combos
it.groupby(data, key=lambda x: x['dept'])
it.islice(range(100), 10) # first 10 items
it.accumulate([1,2,3,4]) # [1,3,6,10]File I/O
Quick reference
| Task | Command |
|---|---|
| Read a file | with open('f.txt') as f: |
| Write a file | open('f.txt', 'w') |
| JSON read/write | json.loads / json.dumps |
| pathlib | Path('dir') / 'file.txt' |
Reading & Writing Files
Read modes and methods
with open('file.txt') as f:
text = f.read() # whole file as str
lines = f.readlines() # list of lines
line = f.readline() # one line
with open('file.txt') as f:
for line in f: # memory-efficient
print(line.strip())Write and append
with open('out.txt', 'w') as f:
f.write('Hello\n')
f.writelines(['a\n', 'b\n'])
with open('out.txt', 'a') as f:
f.write('appended line\n')File mode reference
'r' # read text (default)
'w' # write text (truncates)
'a' # append text
'rb' # read binary
'wb' # write binary
'r+' # read + write
'x' # exclusive create (fails if exists)JSON, CSV & pathlib
JSON read and write
import json
# Parse JSON string
data = json.loads('{"name": "Alice"}')
# Serialize to JSON string
text = json.dumps(data, indent=2)
# Read from file
with open('data.json') as f:
data = json.load(f)
# Write to file
with open('data.json', 'w') as f:
json.dump(data, f, indent=2)CSV read and write
import csv
with open('data.csv') as f:
reader = csv.DictReader(f)
for row in reader:
print(row['name'])
with open('out.csv', 'w', newline='') as f:
w = csv.DictWriter(f, fieldnames=['name', 'age'])
w.writeheader()
w.writerow({'name': 'Alice', 'age': 30})pathlib - modern path operations
from pathlib import Path
p = Path('data') / 'report.txt'
p.exists() # True/False
p.read_text() # read whole file
p.write_text('hello') # write string
p.mkdir(parents=True, exist_ok=True)
p.suffix # '.txt'
p.stem # 'report'
p.parent # Path('data')
list(p.parent.glob('*.txt')) # globError Handling
Quick reference
| Task | Command |
|---|---|
| Catch an exception | try / except ValueError |
| Raise an exception | raise ValueError('msg') |
| Always run cleanup | try / finally |
| Custom exception | class AppError(Exception) |
try / except / else / finally
Full try/except structure
try:
result = risky_operation()
except ValueError as e:
print(f'Value error: {e}')
except (TypeError, KeyError):
print('Type or Key error')
except Exception as e:
print(f'Unexpected: {e}')
else:
print('No exception raised')
finally:
print('Always runs')Raise and re-raise
raise ValueError('bad input')
raise # re-raise current exception
raise RuntimeError('context') from e # chainedCustom exception classes
class AppError(Exception):
pass
class NotFoundError(AppError):
def __init__(self, resource):
self.resource = resource
super().__init__(f'{resource} not found')
raise NotFoundError('user')Context Managers
with statement (context manager)
with open('file.txt') as f:
data = f.read()
# file auto-closed even on exception
with A() as a, B() as b: # multiple
do(a, b)Custom context manager with contextlib
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.time()
try:
yield
finally:
elapsed = time.time() - start
print(f'Elapsed: {elapsed:.3f}s')
with timer():
do_work()Common built-in exceptions
ValueError # wrong value type/format
TypeError # wrong argument type
KeyError # missing dict key
IndexError # list index out of range
AttributeError # object has no attribute
FileNotFoundError # file missing
ZeroDivisionError # division by zero
StopIteration # iterator exhausted
RuntimeError # generic runtime errorModules & Packages
Quick reference
| Task | Command |
|---|---|
| Import stdlib | import os, sys, pathlib |
| Import from module | from module import name |
| Entry point guard | if __name__ == '__main__' |
| Dynamic import | importlib.import_module() |
Import Patterns
Import styles
import math
import numpy as np # alias
from os import path
from os.path import join, exists
from typing import Optional, Listif __name__ == '__main__' guard
def main():
print('Running as script')
if __name__ == '__main__':
main()Key stdlib modules
os, sys, pathlib # filesystem, env
re # regular expressions
json, csv # data formats
datetime, time # dates & timing
collections # Counter, defaultdict, deque
itertools, functools # functional tools
math, random # math & randomness
threading, asyncio # concurrency
subprocess # run shell commands
logging # structured logging
unittest, pytest # testingDecorators
Writing a decorator
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f'Calling {func.__name__}')
result = func(*args, **kwargs)
print(f'Done')
return result
return wrapper
@log_calls
def greet(name):
print(f'Hello {name}')Decorator with arguments
def retry(times=3):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for i in range(times):
try:
return func(*args, **kwargs)
except Exception:
if i == times - 1:
raise
return wrapper
return decorator
@retry(times=5)
def flaky_request(): ...Built-in Functions
Quick reference
| Task | Command |
|---|---|
| Pair two lists | zip(names, scores) |
| Any element matches | any(cond for x in lst) |
| All elements match | all(cond for x in lst) |
| Object attributes | vars(obj) |
Essential Built-ins
Sequence built-ins
len(x) # length
range(n) # integer sequence
enumerate(lst) # (index, value) pairs
zip(a, b) # pair elements
reversed(lst) # reverse iterator
sorted(lst) # new sorted list
list(iterable) # convert to list
tuple(iterable) # convert to tuple
set(iterable) # convert to set
dict(pairs) # convert to dictMath and logic built-ins
abs(x) # absolute value
round(x, n) # round to n decimals
min(a, b, ...) # minimum
max(a, b, ...) # maximum
sum(iterable) # sum
pow(x, y) # x**y
any(iterable) # True if any truthy
all(iterable) # True if all truthyIntrospection built-ins
type(x) # type of x
isinstance(x, T) # is x an instance of T?
issubclass(A, B) # is A a subclass of B?
dir(x) # list attributes/methods
vars(x) # __dict__ of x
hasattr(x, 'n') # does x have attribute n?
getattr(x, 'n') # get attribute by name
setattr(x, 'n', v) # set attribute
callable(x) # is x callable?
id(x) # memory addressI/O and conversion built-ins
print(*args, sep=' ', end='\n')
input(prompt) # read from stdin
open(file, mode) # open file
repr(x) # developer string
str(x) # user string
format(x, spec) # format with spec
chr(65) # 'A'
ord('A') # 65
hex(255) # '0xff'
bin(8) # '0b1000'zip and map patterns
names = ['a', 'b', 'c']
scores = [90, 85, 92]
for name, score in zip(names, scores):
print(name, score)
dict(zip(names, scores))
# {'a': 90, 'b': 85, 'c': 92}
list(map(str, scores))
# ['90', '85', '92']Async / Await
Quick reference
| Task | Command |
|---|---|
| Run async entry point | asyncio.run(main()) |
| Await a coroutine | await some_coroutine() |
| Run concurrently | asyncio.gather(c1, c2) |
| Async context manager | async with ... as f: |
Coroutines & asyncio.run
Define and run a coroutine
import asyncio
async def fetch_data(url):
await asyncio.sleep(1) # simulate I/O
return f'data from {url}'
async def main():
result = await fetch_data('https://example.com')
print(result)
asyncio.run(main())asyncio.gather - run coroutines concurrently
async def main():
# All three run concurrently
r1, r2, r3 = await asyncio.gather(
fetch('url1'),
fetch('url2'),
fetch('url3'),
)
print(r1, r2, r3)
# gather with return_exceptions=True won't raise on partial failure
results = await asyncio.gather(*coros, return_exceptions=True)asyncio.create_task - fire and don't wait
async def main():
task = asyncio.create_task(fetch('url'))
# do other things here...
result = await task # wait when readyasyncio.timeout (Python 3.11+)
import asyncio
async def main():
try:
async with asyncio.timeout(5.0):
result = await slow_operation()
except TimeoutError:
print('Timed out')Async Iteration & Context Managers
async for - iterate over async iterables
async def main():
async for item in async_generator():
print(item)async with - async context manager
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
data = await resp.json()Async generator
async def paginate(url):
page = 1
while True:
data = await fetch(url, page=page)
if not data:
break
yield data
page += 1
async for page in paginate('https://api.example.com'):
process(page)asyncio.Queue - producer/consumer pattern
async def producer(q):
for i in range(5):
await q.put(i)
await asyncio.sleep(0.1)
await q.put(None) # sentinel
async def consumer(q):
while (item := await q.get()) is not None:
print(item)
async def main():
q = asyncio.Queue()
await asyncio.gather(producer(q), consumer(q))aiohttp & aiofiles patterns
Fetch multiple URLs concurrently with aiohttp
import aiohttp, asyncio
async def fetch(session, url):
async with session.get(url) as r:
return await r.text()
async def main(urls):
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, u) for u in urls]
results = await asyncio.gather(*tasks)
return results
asyncio.run(main(['https://a.com', 'https://b.com']))aiofiles - async file I/O
import aiofiles
async def read_file(path):
async with aiofiles.open(path) as f:
return await f.read()
async def write_file(path, data):
async with aiofiles.open(path, 'w') as f:
await f.write(data)Regular Expressions
Quick reference
| Task | Command |
|---|---|
| Find first match | re.search(pattern, text) |
| Find all matches | re.findall(pattern, text) |
| Replace matches | re.sub(pattern, repl, text) |
| Compile for reuse | re.compile(pattern, flags) |
Core re Functions
re.search - find match anywhere in string
import re
m = re.search(r'\d+', 'abc 42 def')
if m:
m.group() # '42'
m.start() # 4
m.end() # 6
m.span() # (4, 6)re.match - match only at start of string
m = re.match(r'\d+', '42 abc') # matches
m = re.match(r'\d+', 'abc 42') # Nonere.findall - return all non-overlapping matches
re.findall(r'\d+', 'a1 b22 c333')
# ['1', '22', '333']
re.findall(r'(\w+)=(\w+)', 'a=1 b=2')
# [('a', '1'), ('b', '2')]re.finditer - iterator of match objects
for m in re.finditer(r'\d+', 'a1 b22 c333'):
print(m.group(), m.start())re.sub - replace matches
re.sub(r'\s+', ' ', 'hello world') # 'hello world'
re.sub(r'(\w+)', r'[\1]', 'a b') # '[a] [b]'
re.sub(r'\d+', lambda m: str(int(m.group())*2), '3 cats')
# '6 cats're.split - split on pattern
re.split(r'[\s,;]+', 'a b,c;;d')
# ['a', 'b', 'c', 'd']re.compile - compile for reuse
pat = re.compile(r'\b[A-Z]\w+', re.IGNORECASE)
pat.search(text)
pat.findall(text)
pat.sub('WORD', text)Groups, Named Groups & Flags
Capture groups
m = re.search(r'(\d{4})-(\d{2})-(\d{2})', '2024-03-15')
m.group(0) # '2024-03-15' (full match)
m.group(1) # '2024'
m.group(2) # '03'
m.groups() # ('2024', '03', '15')Named groups with (?P<name>…)
m = re.search(
r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})',
'2024-03-15'
)
m.group('year') # '2024'
m.groupdict() # {'year': '2024', 'month': '03', 'day': '15'}Common flags
re.IGNORECASE # re.I - case-insensitive
re.MULTILINE # re.M - ^ and $ match line start/end
re.DOTALL # re.S - . matches newline too
re.VERBOSE # re.X - allow whitespace and comments
# Combine flags:
re.compile(r'\w+', re.I | re.M)
# Inline flag in pattern:
re.search(r'(?i)hello', text)Lookahead and lookbehind
# Positive lookahead: followed by
re.findall(r'\d+(?= dollars)', '100 dollars 50 euros')
# ['100']
# Negative lookahead: not followed by
re.findall(r'\d+(?! dollars)', '100 dollars 50 euros')
# ['50']
# Positive lookbehind: preceded by
re.findall(r'(?<=\$)\d+', '$100 €50')
# ['100']Common Patterns
Email, URL, phone
# Email (simplified)
r'[\w.+-]+@[\w-]+\.[a-z]{2,}'
# URL
r'https?://[\w/:%#@$&?()~.=+-]+'
# US phone
r'\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}'
# IPv4
r'\b(?:\d{1,3}\.){3}\d{1,3}\b'Verbose pattern with comments
date_pat = re.compile(r"""
(?P<year> \d{4}) - # four-digit year
(?P<month> \d{2}) - # two-digit month
(?P<day> \d{2}) # two-digit day
""", re.VERBOSE)Type Hints
Quick reference
| Task | Command |
|---|---|
| Annotate a function | def f(x: int) -> str |
| Optional value | Optional[str] / str | None |
| Typed dict | class User(TypedDict) |
| Protocol (structural) | class P(Protocol) |
Basic Annotations
Variable and function annotations
x: int = 42
name: str = 'Alice'
items: list[int] = []
mapping: dict[str, int] = {}
def process(data: list[str]) -> dict[str, int]:
return {s: len(s) for s in data}Optional and Union
from typing import Optional, Union
# Old style (all versions)
def find(key: str) -> Optional[str]: ...
# New style (Python 3.10+)
def find(key: str) -> str | None: ...
# Union of types
def parse(val: str | int | float) -> str: ...Common generic types
from typing import Sequence, Mapping, Callable, Iterator, Generator
def total(nums: Sequence[int]) -> int: ...
def apply(fn: Callable[[int], str], x: int) -> str:
return fn(x)
def count() -> Iterator[int]:
i = 0
while True:
yield i
i += 1Literal and Final
from typing import Literal, Final
# Only these specific values are allowed
Mode = Literal['r', 'w', 'a']
def open_file(path: str, mode: Mode) -> None: ...
# Constant that must not be reassigned
MAX_RETRIES: Final = 3TypedDict, Protocol & TypeVar
TypedDict - typed dict shape
from typing import TypedDict, NotRequired
class User(TypedDict):
name: str
age: int
email: NotRequired[str] # optional key
user: User = {'name': 'Alice', 'age': 30}Protocol - structural subtyping (duck typing with types)
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
# Any class with draw() satisfies Drawable
# without explicitly inheriting from it
def render(shape: Drawable) -> None:
shape.draw()TypeVar - generic functions
from typing import TypeVar
T = TypeVar('T')
def first(items: list[T]) -> T:
return items[0]
# Bounded TypeVar
N = TypeVar('N', int, float)
def double(x: N) -> N:
return x * 2@overload - multiple call signatures
from typing import overload
@overload
def process(x: int) -> int: ...
@overload
def process(x: str) -> str: ...
def process(x): # actual implementation
if isinstance(x, int):
return x * 2
return x.upper()from __future__ import annotations (postponed evaluation)
from __future__ import annotations
# Allows forward references without quotes
class Node:
def __init__(self, next: Node | None = None):
self.next = next # Node not yet defined aboveNothing matches. Try a single word.
You already know that syntax errors and forgotten method names waste time. A good Python cheat sheet fixes that fast.
Python is flexible, readable, and used everywhere from data science to web development. But even experienced developers blank on slicing syntax or can't remember if it's .append() or .add().
This guide covers the core reference points you actually reach for:
-
Data types and variable syntax
-
Built-in functions and string methods
-
Loops, conditionals, and list comprehension
-
File handling, error handling, and OOP basics
-
Quick-reference snippets for Python 3
No fluff. Just the Python quick reference you need to write cleaner scripts faster.
What is Python
Python is a high-level, interpreted programming language built around readability and clean syntax.
Guido van Rossum created it in 1991. The Python Software Foundation maintains it today.
Python 3 is the current standard. Python 2 hit end-of-life in 2020, so unless you're maintaining legacy code, there's no reason to touch it.
It covers scripting, automation, data science (NumPy, Pandas), web development (Django, Flask), and machine learning. The Python Package Index (PyPI) holds over 450,000 packages, all installable via pip.
Python Syntax Basics
Python uses indentation instead of braces to define code blocks. The interpreter enforces this. Get it wrong and the script fails immediately.
Variables and Data Types
No type declarations needed. Variables are assigned directly and can hold any data type.
Core built-in types:
-
int,float- whole numbers and decimals -
str- text strings -
bool-TrueorFalse -
list,tuple,dict,set- collection types
Type conversion uses built-in functions: int(), str(), float(), list(). No imports needed.
Comments
Single-line comments use #. Multi-line comments use triple quotes (''' or """), though technically those are string literals, not real comments.
# Single-line comment
'''
This spans
multiple lines
'''
PEP 8 recommends keeping comments short and updated when code changes.
Indentation Rules
Four spaces per level is the PEP 8 standard. Tabs work, but mixing tabs and spaces in Python 3 throws a TabError.
Common mistakes: forgetting to indent after a colon, inconsistent spacing, copy-pasting code with mismatched indentation from another editor.
IndentationError and TabError are the two exceptions Python raises when indentation is wrong. Both are easy to spot once you know what you're looking for.
Python Operators
Arithmetic Operators
Standard math plus a few Python-specific ones:
|
Operator |
Operation |
Example |
|---|---|---|
|
|
Addition |
|
|
|
Subtraction |
|
|
|
Multiplication |
|
|
|
Division (float) |
|
|
|
Floor division |
|
|
|
Modulus |
|
|
|
Exponent |
|
// and ** are the ones people forget. // floors the result; ** handles powers.
Comparison Operators
Return True or False. Used in conditionals and loops.
==, !=, >, <, >=, <=
Note: == checks value equality. is checks object identity. They're not the same thing.
Logical Operators
and, or, not - combine or invert boolean expressions.
x = 5
print(x > 2 and x < 10) # True
print(not x > 10) # True
Assignment Operators
= assigns. Shorthand operators modify and reassign in one step:
+=, -=, *=, /=, //=, %=, **=
x = 10
x += 5 # x is now 15
x **= 2 # x is now 225
Bitwise Operators
Work on binary representations of integers. Less common in general scripting, but useful in systems programming and data processing.
& (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift)
Python Data Types
Strings
String methods don't modify the original. They return a new string.
Common methods:
-
.upper(),.lower()- change case -
.strip()- remove leading/trailing whitespace -
.split(separator)- split into a list -
.replace(old, new)- swap substrings -
.format()- insert values into a template -
f-strings - the cleanest way to format strings in Python 3.6+
name = "python"
print(name.upper()) # PYTHON
print(f"Hello, {name}!") # Hello, python!
f-strings are faster and more readable than .format(). Use them by default.
Lists
Ordered, mutable, allows duplicates.
Key methods:
-
.append(item)- add to end -
.remove(item)- remove first match -
.pop(index)- remove and return item -
.sort()- sort in place -
.reverse()- reverse in place
fruits = ["apple", "banana", "cherry"]
fruits.append("mango")
fruits.sort()
print(fruits[1:3]) # list slicing
List slicing syntax: list[start:stop:step]. The stop index is exclusive.
Tuples
Like lists but immutable. Once created, the values can't change.
coords = (10.5, 20.3)
Use tuples for data that shouldn't change: coordinates, RGB values, database records. Slightly faster than lists for iteration.
Dictionaries
Key-value pairs. Keys must be unique and immutable.
Core methods:
-
.get(key)- returns value orNone(no KeyError) -
.keys(),.values(),.items()- views of the dict -
Dict comprehension:
{k: v for k, v in iterable}
user = {"name": "Alex", "age": 30}
print(user.get("email", "N/A")) # N/A
.get() is safer than direct key access when the key might not exist.
Sets
Unordered, no duplicates. Good for membership testing and removing duplicates from a list.
-
.add(item),.remove(item) -
|union,&intersection,-difference
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b) # {3}
print(a | b) # {1, 2, 3, 4, 5}
Python Control Flow
if / elif / else Statements
Python's conditional syntax is straightforward. No parentheses required around the condition, but the colon is mandatory.
score = 72
if score >= 90:
print("A")
elif score >= 70:
print("C")
else:
print("F")
Conditions can use comparison operators, logical operators, in, not in, is, and is not.
for Loops
Iterates over any iterable: lists, strings, dicts, ranges.
for i in range(5):
print(i)
for fruit in ["apple", "banana"]:
print(fruit)
range(start, stop, step) - stop is exclusive.
enumerate() gives both index and value:
for i, val in enumerate(["a", "b", "c"]):
print(i, val)
while Loops
Runs as long as the condition is True. Use break to exit early, continue to skip to the next iteration, pass as a placeholder.
x = 0
while x < 5:
x += 1
if x == 3:
continue
print(x)
Infinite loops happen when the condition never becomes False. Always make sure something inside the loop changes the condition.
List Comprehensions
One-liner syntax for building lists. Faster than a regular for loop in most cases.
# Basic
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# Nested
matrix = [[i * j for j in range(3)] for i in range(3)]
List comprehension syntax: [expression for item in iterable if condition]
The condition is optional. Nesting works but gets hard to read quickly - keep it to two levels max.
Python Functions
Functions are defined with def. No function body means a SyntaxError - use pass as a placeholder if needed.
def greet(name):
return f"Hello, {name}!"
Defining and Calling Functions
Define once, call anywhere. Function names follow snake_case by convention (PEP 8).
def add(a, b):
return a + b
result = add(3, 5) # 8
Arguments and Parameters
Python gives you four ways to pass data into a function:
-
Positional - order matters:
add(3, 5) -
Keyword - name matters, order doesn't:
add(b=5, a=3) -
Default - fallback value if argument is omitted:
def greet(name="user") -
*args- variable positional arguments (tuple);**kwargs- variable keyword arguments (dict)
def log(*args, **kwargs):
print(args, kwargs)
log("error", code=404, path="/home")
Lambda Functions
Single-expression anonymous functions. Useful inline, terrible for anything complex.
square = lambda x: x ** 2
print(square(4)) # 16
Common use: passing a function as an argument to sorted(), map(), or filter().
Return Values
A function without a return statement returns None. Multiple values can be returned as a tuple.
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([3, 1, 9, 2])
Python Built-in Functions
No import needed. These ship with every Python 3 installation.
|
Function |
What it does |
|---|---|
|
|
Output to console |
|
|
Length of an object |
|
|
Generate a number sequence |
|
|
Return object type |
|
|
Read user input (returns str) |
|
|
Type conversion |
|
|
Convert to collection type |
|
|
Pair items from two iterables |
|
|
Apply function to iterable |
|
|
Filter iterable by condition |
|
|
Return sorted copy |
|
|
Add index to iterable |
|
|
Math on iterables |
|
|
Absolute value, rounding |
zip() stops at the shortest iterable. map() and filter() return iterators, not lists - wrap in list() to see the result.
Python Modules and Imports
import and from...import
import math
print(math.sqrt(16)) # 4.0
from math import sqrt
print(sqrt(16)) # 4.0
import numpy as np # aliased import
from module import * pulls everything into the namespace. Avoid it - name collisions are a pain to debug.
Commonly Used Standard Library Modules
No pip install needed. Part of Python's standard library.
-
os- file system operations, environment variables -
sys- interpreter info, command-line args (sys.argv) -
math-sqrt,ceil,floor,pi,log -
random-random(),randint(),choice(),shuffle() -
datetime- dates, times, timedeltas -
json- parse and serialize JSON -
re- regular expressions -
collections-Counter,defaultdict,deque,OrderedDict
Python File Handling
Opening and Reading Files
f = open("file.txt", "r")
content = f.read()
f.close()
Always close the file. Or better, use with - it closes automatically. For reading and writing JSON files with json.load and json.dump, including dates, Decimals, dataclasses and pydantic, see the JSON cheat sheet.
Writing to Files
with open("output.txt", "w") as f:
f.write("Hello\n")
"w" overwrites. "a" appends. Both create the file if it doesn't exist.
Using with Statements
with open() is the standard pattern. Handles closing even if an exception is raised mid-operation.
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
File Modes
|
Mode |
Behavior |
|---|---|
|
|
Read (default) |
|
|
Write, overwrite |
|
|
Append |
|
|
Binary read/write |
|
|
Read and write |
Binary mode (rb, wb) is needed for images, PDFs, and other non-text files.
Python Error Handling
try / except / else / finally
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print("No error")
finally:
print("Always runs")
else runs only if no exception was raised. finally runs regardless - useful for cleanup.
Common Built-in Exceptions
-
ValueError- right type, wrong value (int("abc")) -
TypeError- wrong type entirely ("text" + 5) -
KeyError- missing dict key -
IndexError- list index out of range -
AttributeError- attribute doesn't exist on the object -
FileNotFoundError- file path doesn't exist
Catch specific exceptions, not bare except:. Bare except catches everything including KeyboardInterrupt.
Raising Exceptions
def set_age(age):
if age < 0:
raise ValueError("Age can't be negative")
return age
Use raise to enforce constraints. Custom exception classes inherit from Exception.
Python Classes and Object-Oriented Programming
Python is multi-paradigm. OOP is optional, but understanding it is necessary for working with most Python libraries and frameworks.
Defining a Class
class Dog:
species = "Canis familiaris" # class attribute
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age
init and self
__init__ runs automatically when an instance is created. self refers to the instance - it must be the first parameter of every instance method, but you don't pass it explicitly when calling.
rex = Dog("Rex", 4)
print(rex.name) # Rex
Instance Methods vs Class Methods vs Static Methods
-
Instance methods - access
self; most common -
@classmethod- accesscls; used for alternative constructors -
@staticmethod- no access to instance or class; utility functions
class Circle:
def area(self):
return 3.14 * self.radius ** 2
@classmethod
def from_diameter(cls, d):
return cls(d / 2)
@staticmethod
def is_valid_radius(r):
return r > 0
Inheritance
class Animal:
def speak(self):
return "..."
class Cat(Animal):
def speak(self):
return "Meow"
Child classes override parent methods. super() calls the parent's version.
Magic Methods
Also called dunder methods. Python calls them automatically in specific contexts.
-
__str__- called byprint()andstr() -
__repr__- unambiguous representation, used in the REPL -
__len__- called bylen() -
__eq__- defines==behavior -
__init__- constructor
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return self.title
def __repr__(self):
return f"Book('{self.title}')"
Python List and Dictionary Comprehensions
List Comprehension Syntax
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
Faster than for loops for simple transformations. Harder to read past two conditions.
Dictionary Comprehension Syntax
word_lengths = {word: len(word) for word in ["python", "code", "cheat"]}
inverted = {v: k for k, v in original.items()}
Dictionary comprehension follows the same pattern as list comprehension, with {key: value for ...}.
Nested Comprehensions
matrix = [[i * j for j in range(3)] for i in range(3)]
flat = [x for row in matrix for x in row]
Keep nesting to two levels. Beyond that, use a regular loop.
Python String Formatting
Three approaches exist. f-strings are the modern standard.
f-Strings (Python 3.6+)
name = "Alex"
score = 98.5
print(f"{name} scored {score:.1f}") # Alex scored 98.5
Supports expressions, method calls, and format specifiers inside {}. Fastest of the three options.
.format() Method
"{} scored {}".format("Alex", 98.5)
"{name} scored {score}".format(name="Alex", score=98.5)
Still widely used in older codebases. Works in Python 2 and 3.
% Formatting (Legacy)
"Hello, %s. You are %d years old." % ("Alex", 30)
Old-style C formatting. Still works but avoid it in new code.
Python Regular Expressions
re Module Basics
import re
All regex operations go through the re module. Patterns are raw strings (r"pattern") to avoid backslash conflicts.
Common Patterns
|
Pattern |
Matches |
|---|---|
|
|
Any character except newline |
|
|
Digit (0-9) |
|
|
Word character (letters, digits, |
|
|
Whitespace |
|
|
Start of string |
|
|
End of string |
|
|
0 or more |
|
|
1 or more |
|
|
0 or 1 (optional) |
|
|
Between n and m times |
re.match(), re.search(), re.findall(), re.sub()
-
re.match()- matches at the start of the string only -
re.search()- scans the whole string, returns first match -
re.findall()- returns all matches as a list -
re.sub(pattern, replacement, string)- find and replace
text = "Order #1042 placed on 2024-03-15"
dates = re.findall(r"\d{4}-\d{2}-\d{2}", text)
clean = re.sub(r"#\d+", "[ID]", text)
Python Sorting and Searching
sorted() vs .sort()
sorted() returns a new list. .sort() modifies in place and returns None.
nums = [3, 1, 4, 1, 5]
print(sorted(nums)) # [1, 1, 3, 4, 5] - original unchanged
nums.sort(reverse=True) # [5, 4, 3, 1, 1] - modified in place
Sorting by Key
users = [{"name": "Bob", "age": 25}, {"name": "Ana", "age": 30}]
users.sort(key=lambda x: x["age"])
words = ["banana", "fig", "apple"]
words.sort(key=len)
The key parameter accepts any callable. Works with both sorted() and .sort().
Searching in Lists and Dicts
nums = [10, 20, 30]
print(20 in nums) # True - membership test
print(nums.index(30)) # 2 - index of first match
data = {"user": "Alex"}
print("user" in data) # True - checks keys
print("Alex" in data.values()) # True - checks values
in on a list is O(n). in on a set or dict is O(1). For large datasets, convert to a set first.
Python Virtual Environments and Package Management
Creating a Virtual Environment
python -m venv env
source env/bin/activate # macOS/Linux
env\Scripts\activate # Windows
Virtual environments isolate project dependencies. Without one, packages install globally and version conflicts become a real problem.
Installing Packages with pip
pip install requests
pip install django==4.2.0 # specific version
pip uninstall requests
pip list # show installed packages
pip show requests # details on one package
pip pulls from PyPI (Python Package Index). Most Python libraries live there, including Requests, Matplotlib, and NumPy.
requirements.txt
pip freeze > requirements.txt # save current environment
pip install -r requirements.txt # recreate environment
Commit requirements.txt to version control. Skip the env/ folder itself - it's machine-specific and usually large.
FAQ on Python Cheat Sheets
What should a Python cheat sheet include?
A solid Python cheat sheet covers syntax basics, data types, built-in functions, control flow, and string methods.
Include operators, list and dictionary comprehensions, file handling, and error handling. The more complete the reference, the less time you spend searching Stack Overflow.
What is the difference between a list and a tuple in Python?
Lists are mutable. Tuples are immutable - once created, values can't change.
Use lists when data needs to change; use tuples for fixed data like coordinates or database records. Tuples are slightly faster to iterate.
How do you handle errors in Python?
Use try, except, else, and finally blocks.
Catch specific exceptions like ValueError or KeyError rather than a bare except. Bare except catches everything, including keyboard interrupts, which causes harder-to-diagnose bugs.
What are Python f-strings and when should you use them?
f-strings (Python 3.6+) are the fastest and most readable string formatting option.
Write f"{variable}" to insert values directly into a string. They support expressions, method calls, and format specifiers inside the curly braces. Use them by default.
What is the difference between sorted() and .sort() in Python?
sorted() returns a new list and leaves the original unchanged. .sort() modifies the list in place and returns None.
Both accept a key parameter for custom sorting logic.
How do Python virtual environments work?
A virtual environment isolates project dependencies so packages don't conflict across projects.
Create one with python -m venv env, activate it, then install packages with pip. Always add requirements.txt to version control using pip freeze.
What are the most useful Python built-in functions?
len(), range(), zip(), enumerate(), sorted(), map(), and filter() cover most everyday use cases.
None require an import. enumerate() is the one beginners skip most often - it gives both index and value in a single loop.
What is list comprehension in Python?
List comprehension is a one-line syntax for building lists: [expression for item in iterable if condition].
It's faster than a standard for loop for simple transformations. Dictionary and set comprehensions follow the same pattern with minor syntax changes.
What Python modules should beginners know?
Start with os, sys, math, random, datetime, and json - all part of Python's standard library, no pip install needed.
For data work, add NumPy and Pandas. For web projects, Requests and Flask or Django cover most needs.
What is the difference between == and is in Python?
== compares values. is compares object identity - whether two variables point to the exact same object in memory.
"hello" == "hello" is True. Whether "hello" is "hello" is True depends on Python's string interning. Don't use is for value comparisons.