Python Cheat Sheet
A searchable, printable Python 3 reference — syntax, data structures, comprehensions, functions, classes, files and the standard library. Free.
Variables & types
10x = 1
x: int = 1
a, b = 1, 2
type(x)
int('42')
str(42)
isinstance(x, int)
None
x = y = 0
PI: Final = 3.14
Strings
11f'Hello {name}'
len(s)
s.upper()
s.strip()
s.split(',')
','.join(items)
s.replace('a', 'b')
'a' in s
s[1:4]
s[::-1]
s.startswith('a')
Lists & tuples
10a = [1, 2, 3]
a.append(4)
a.insert(0, x)
a.pop()
a[1:3]
sorted(a, reverse=True)
a.sort(key=len)
len(a)
t = (1, 2)
first, *rest = a
Dicts & sets
10d = {'k': 'v'}
d['k']
d.get('k', default)
d.keys() / d.values()
d.items()
{**a, **b}
a | b
del d['k']
s = {1, 2, 3}
set(a) & set(b)
Comprehensions
8[x * 2 for x in a]
[x for x in a if x > 0]
{x: x**2 for x in a}
{x for x in a}
(x for x in a)
[y for row in m for y in row]
[a if c else b for x in items]
sum(x for x in a)
Control flow
9if x > 0:\n ...
elif / else:
a if cond else b
for x in range(10):
for i, x in enumerate(a):
for a, b in zip(x, y):
while cond:
break / continue
match x:\n case 1: ...
Functions
8def f(a, b=1): return a + b
def f(*args, **kwargs):
f(name='Sam')
lambda x: x + 1
def f(a: int) -> int:
@decorator
yield value
global x / nonlocal x
Classes
9class A(Base):
def __init__(self, x):
self.x = x
def __str__(self):
@property
@staticmethod / @classmethod
super().__init__()
@dataclass
isinstance(obj, A)
Files, errors & modules
9with open('f.txt') as fh:
fh.read() / fh.readlines()
open('f.txt', 'w').write(s)
try:\n ...\nexcept ValueError as e:
raise ValueError('bad')
finally:
import os
from math import sqrt
import numpy as np
No entry matches “:q”.
About Python Cheat Sheet
This Python cheat sheet compresses Python 3 into one searchable page: variables and types, strings, lists and tuples, dicts and sets, comprehensions, control flow, functions, classes, and files, errors and modules. Each row shows working code with a short explanation.
It leans on idiomatic Python — f-strings, slicing, list and dict comprehensions, unpacking, default and keyword arguments, context managers and exception handling — which makes it a fast refresher whether Python is your daily language or the one you return to occasionally.
The sheet is free and entirely client-side. Filter it live from the search box, navigate with the sticky section menu, copy any snippet with a single click and print the whole reference when you want it next to your keyboard.
How to use Python Cheat Sheet
- Skim the sections — Variables & types through Comprehensions to Files, errors & modules.
- Type into the search box to filter every snippet live across the whole sheet.
- Jump to a section such as Dicts & sets using the sticky table of contents.
- Click any snippet or its copy icon to copy the Python code.
- Print the page for an offline Python 3 reference.