Python Cheat Sheet

Free Python cheat sheet: syntax, data structures, control flow, and functions at a glance — searchable and beginner-friendly.

Data Types

ConceptSyntaxExample
String
Text — any sequence of characters wrapped in quotes.
strname = 'Alice'
Integer
Whole numbers — no decimal point.
intage = 30
Float
Numbers with a decimal point.
floatprice = 9.99
Boolean
True or False — used for conditions and logic.
boolactive = True
None
Represents the absence of a value (like null in other languages).
Noneresult = None

Learn it in a lesson: Variables and Data Types · None & NoneType

Collections

ConceptSyntaxExample
List
Ordered, changeable sequence of items. Use for ordered collections.
[1, 2, 3]nums = [1, 2, 3]; nums.append(4)
Dictionary
Key-value store for fast lookup by name. Like a real dictionary.
{'key': 'val'}d = {'a': 1}; d['b'] = 2
Tuple
Like a list but immutable (can't change it). Good for fixed data like coordinates.
(1, 2, 3)point = (10, 20)
Set
Unordered collection of unique values — automatically removes duplicates.
{1, 2, 3}unique = {1, 2, 2, 3} # {1, 2, 3}

Learn it in a lesson: Lists and Collections · Dictionaries · Tuples · Sets

Control Flow

ConceptSyntaxExample
If/Elif/Else
Make decisions in your code based on conditions.
if x > 0: ... elif: ... else:if age >= 18: print('Adult')
For loop
Repeat code for each item in a list, string, or range.
for item in iterable:for i in range(10): print(i)
While loop
Keep repeating as long as a condition is True.
while condition:while count > 0: count -= 1
Comprehension
Compact way to create a list — combines a loop and expression in one line.
[expr for x in iter if cond][x**2 for x in range(5)]

Learn it in a lesson: Control Flow - If/Else · Loops - For and While · Comprehensions

Functions

ConceptSyntaxExample
Define function
Create a reusable block of code. Call it by name whenever needed.
def fn(params):def add(a, b): return a + b
Lambda
A tiny one-line anonymous function — good for simple transformations.
lambda params: exprsquare = lambda x: x**2
Default args
Provide fallback values for parameters if the caller doesn't supply them.
def fn(x=10):def greet(name='World'): ...
Return multiple
Python can return multiple values as a tuple — unpack them on the calling side.
return a, bdef divide(a,b): return a//b, a%b
*args
Accept any number of positional arguments, collected into a tuple.
def fn(*args):def total(*nums): return sum(nums)
**kwargs
Accept any number of keyword arguments, collected into a dict.
def fn(**kwargs):def make(**opts): return opts
Type hints
Optional annotations that document expected types (not enforced at runtime).
def fn(x: int) -> str:def greet(name: str) -> str: return 'Hi ' + name

Learn it in a lesson: Functions · Lambda Functions · *args & **kwargs · Type Hints & Static Typing with mypy

Strings

ConceptSyntaxExample
F-string
Embed expressions directly inside a string. The cleanest way to format.
f'text {var}'name = 'Al'; print(f'Hi {name}, {2+2}')
Format number
Control decimals, width, and padding inside an f-string.
f'{x:.2f}'f'{3.14159:.2f}' # '3.14'
Upper / lower
Change the case of a string. Returns a new string.
s.upper() / s.lower()'Hi'.upper() # 'HI'
Strip whitespace
Remove leading/trailing whitespace (or given chars).
s.strip()' hi '.strip() # 'hi'
Replace
Swap every occurrence of a substring for another.
s.replace(old, new)'a-b-c'.replace('-', '_') # 'a_b_c'
Split / join
Split turns a string into a list; join glues a list back into a string.
s.split(sep) / sep.join(list)'a,b'.split(',') # ['a','b']
Find / contains
Check membership with `in`; `.find()` returns the index or -1.
sub in s / s.find(sub)'cat' in 'concatenate' # True
Starts / ends with
Quick prefix/suffix checks — handy for filenames and URLs.
s.startswith(x) / s.endswith(x)'file.py'.endswith('.py') # True
Slice
Extract a substring; negative indices count from the end.
s[start:stop:step]'hello'[1:4] # 'ell'

Learn it in a lesson: String Methods · f-strings & String Formatting · Slicing Lists & Strings

Lists & Comprehensions

ConceptSyntaxExample
Append / extend
append adds one item; extend adds every item of an iterable.
lst.append(x) / lst.extend(it)nums = [1]; nums.append(2); nums.extend([3,4])
Insert / remove
Insert at a position; remove deletes the first matching value.
lst.insert(i, x) / lst.remove(x)lst = [1,3]; lst.insert(1, 2) # [1,2,3]
Pop
Remove and return an item (last by default, or at index i).
lst.pop(i)lst = [1,2,3]; lst.pop() # 3
Sort
.sort() mutates in place; sorted() returns a new list.
lst.sort() / sorted(lst)sorted([3,1,2]) # [1,2,3]
Reverse
Slicing makes a reversed copy; .reverse() flips in place.
lst[::-1] / lst.reverse()[1,2,3][::-1] # [3,2,1]
List comprehension
Build a list in one line by looping and optionally filtering.
[expr for x in it if cond][x*x for x in range(5) if x % 2 == 0]
Nested comprehension
Flatten nested lists by chaining two for clauses.
[x for row in grid for x in row][c for row in [[1,2],[3]] for c in row] # [1,2,3]
Unpack
Star unpacking grabs the rest of a sequence into a list.
a, *rest = lstfirst, *rest = [1,2,3,4] # 1, [2,3,4]

Learn it in a lesson: Lists and Collections · Comprehensions · Unpacking & Star Expressions

Dicts & Sets

ConceptSyntaxExample
Get with default
Look up a key without raising KeyError if it's missing.
d.get(key, default){'a':1}.get('b', 0) # 0
Keys / values / items
Iterate over keys, values, or key-value pairs of a dict.
d.keys() / d.values() / d.items()for k, v in d.items(): print(k, v)
Dict comprehension
Build a dict in one line by looping over an iterable.
{k: v for ... in ...}{x: x*x for x in range(4)}
Merge dicts
Combine two dicts; later keys win on conflict (Python 3.9+ uses |).
{**a, **b} or a | b{**{'x':1}, **{'y':2}}
Set operations
Intersection (&), union (|), difference (-) of sets.
a & b, a | b, a - b{1,2,3} & {2,3,4} # {2,3}
Deduplicate
Convert to a set to drop duplicates (order not preserved).
set(list)list(set([1,1,2,3])) # [1,2,3]
Setdefault
Get a key's value, inserting a default first if it's absent.
d.setdefault(k, default)d = {}; d.setdefault('x', []).append(1)

Learn it in a lesson: Dictionary Methods Deep Dive · Sets

Loops & Iteration

ConceptSyntaxExample
Enumerate
Loop with an automatic index counter alongside each item.
for i, x in enumerate(it):for i, c in enumerate('ab'): print(i, c)
Zip
Iterate over multiple sequences in parallel, pairwise.
for a, b in zip(l1, l2):for n, s in zip([1,2], ['a','b']): print(n, s)
Range
Generate a sequence of numbers — common for counting loops.
range(start, stop, step)list(range(0, 10, 2)) # [0,2,4,6,8]
Break / continue
break exits the loop; continue skips to the next iteration.
break / continuefor x in nums: if x < 0: continue if x > 100: break
Reversed
Iterate a sequence back to front without copying it.
for x in reversed(it):for x in reversed([1,2,3]): print(x)
Else on loop
The else block runs only if the loop finished without break.
for ...: ... else:for x in nums: if x == target: break else: print('not found')

Learn it in a lesson: Loops - For and While · enumerate & zip

Exceptions

ConceptSyntaxExample
Try / except
Catch errors so your program doesn't crash.
try: ... except E: ...try: int('x') except ValueError: print('bad')
Multiple excepts
Catch several exception types in one handler.
except (A, B):except (KeyError, IndexError): handle()
Else / finally
else runs only if try raised nothing; finally always runs (cleanup).
try: ... else: ... finally: ...try: n = int(text) except ValueError: n = 0 else: print('read', n) finally: print('done')
Raise
Trigger an exception deliberately when input is invalid.
raise E('msg')if x < 0: raise ValueError('negative')
Access the error
Bind the exception object to inspect its message or attributes.
except E as e:except ValueError as e: print(e)
Custom exception
Define your own exception types by subclassing Exception.
class E(Exception): passclass TooBig(Exception): pass

Learn it in a lesson: Exception Handling · Custom Exceptions & Exception Chaining

Files & with

ConceptSyntaxExample
Read file
with auto-closes the file even if an error occurs.
with open(path) as f: f.read()with open('a.txt') as f: text = f.read()
Read lines
Iterate a file line by line — memory efficient for big files.
for line in f:with open('a.txt') as f: for line in f: print(line.strip())
Write file
'w' overwrites; 'a' appends to the end of the file.
open(path, 'w')with open('out.txt', 'w') as f: f.write('hi')
Read all lines
Every line of the file as a list of strings, each keeping its \n; the last has one only if the file ends with a line break.
f.readlines()with open('a.txt', encoding='utf-8') as f: lines = f.readlines()
Pathlib read
Modern one-liner to read a whole file as a string.
Path(p).read_text()from pathlib import Path Path('a.txt').read_text()

Learn it in a lesson: File Handling · Modern File Paths with pathlib

Classes

ConceptSyntaxExample
Define class
__init__ is the constructor; self refers to the instance.
class Name:class Dog: def __init__(self, name): self.name = name
Method
Functions defined inside a class; the first parameter, by convention self, is the object the method was called on.
def method(self):class Dog: def bark(self): return 'woof'
Inheritance
Reuse and extend another class's attributes and methods.
class Child(Parent):class Pup(Dog): pass
super()
Call the parent class's version of a method.
super().__init__(...)class Pup(Dog): def __init__(self, n): super().__init__(n)
String repr
Customize how an object prints and shows in the REPL.
def __repr__(self):def __repr__(self): return f'Dog({self.name!r})'
Operator method
a + b calls a's __add__; NotImplemented lets Python ask the other side, then raise TypeError.
def __add__(self, other):def __add__(self, other): if not isinstance(other, Money): return NotImplemented return Money(self.pence + other.pence)
Ordering
Writes <=, > and >= from __eq__ and one ordering method.
@functools.total_ordering@functools.total_ordering class Score: def __eq__(self, other): ... def __lt__(self, other): ...
MRO
The order Python searches a class and its parents; super() calls the class after the current one in it.
Class.__mro__class Copier(Printer, Scanner): pass print([c.__name__ for c in Copier.__mro__])
Dataclass
Auto-generates __init__, __repr__, and __eq__ from fields.
@dataclassfrom dataclasses import dataclass @dataclass class Point: x: int y: int
Class vs instance attr
Class attributes are shared; instance attributes belong to each object.
ClassName.attr vs self.attrclass C: count = 0 # shared def __init__(self): self.id = 1 # per-object

Learn it in a lesson: Object-Oriented Programming · Inheritance and Polymorphism · Magic Methods & the Python Data Model · Operator Overloading & Custom Behaviours · Mixins, Multiple Inheritance & OOP Patterns · Data Classes & Advanced Class Patterns

Useful Builtins

ConceptSyntaxExample
Map
Apply a function to every item; usually a comprehension reads cleaner.
map(fn, iterable)list(map(str, [1,2,3])) # ['1','2','3']
Filter
Keep only items where the function returns True.
filter(fn, iterable)list(filter(lambda x: x>0, [-1,2,-3])) # [2]
Sorted with key
Sort by a computed value; reverse=True for descending.
sorted(it, key=fn, reverse=...)sorted(words, key=len, reverse=True)
Any / all
any: at least one truthy; all: every item truthy.
any(it) / all(it)all(x > 0 for x in nums)
Sum / min / max
Aggregate numbers (or anything comparable) in one call.
sum(it), min(it), max(it)max([3,1,2]) # 3
Enumerate / zip
Pair items with indices, or combine sequences into pairs.
enumerate(it) / zip(a, b)dict(zip(['a','b'], [1,2]))

Learn it in a lesson: Lambda Functions · Booleans & Truthiness · Lists and Collections · enumerate & zip

Standard Library

ConceptSyntaxExample
Counter
Count occurrences of items quickly; .most_common() ranks them.
from collections import CounterCounter('aabbbc') # Counter({'b': 3, 'a': 2, 'c': 1})
defaultdict
A dict that auto-creates a default value for missing keys.
from collections import defaultdictd = defaultdict(list); d['k'].append(1)
deque
Fast appends/pops from both ends — ideal for queues.
from collections import dequeq = deque([1,2]); q.appendleft(0)
itertools
Tools for combinatorics and iteration: product, permutations, chain.
from itertools import ...from itertools import combinations list(combinations([1,2,3], 2))
JSON
Serialize Python objects to JSON text and back.
json.dumps / json.loadsimport json json.dumps({'a': 1}) # '{"a": 1}'
datetime
Work with dates and times; strftime formats them as text.
from datetime import datetimedatetime.now().strftime('%Y-%m-%d')
Import
import gives you the module's name; from ... import gives you just the names you list; as renames either.
import m / from m import name / import m as aliasimport math from math import sqrt import datetime as dt
random
Random whole numbers, choices and shuffles; use the secrets module for passwords.
import randomrandom.randint(1, 6)
Regex
Pattern matching: search, findall, sub for find-and-replace.
import re; re.findall(pat, s)re.findall(r'\d+', 'a1b22') # ['1','22']
Thread pool
submit() hands back a Future at once; result() waits for the value, or raises the task's error.
pool.submit(fn, *args)from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor() as pool: future = pool.submit(pow, 2, 10) print(future.result())
Profile code
Counts every function's calls and time; print_stats(5) shows the first five rows.
with cProfile.Profile() as p:import cProfile, pstats with cProfile.Profile() as p: main() pstats.Stats(p).sort_stats("cumulative").print_stats(5)
Measure memory
Bytes allocated since start() that are still in use, and the most at once.
tracemalloc.get_traced_memory()import tracemalloc tracemalloc.start() data = list(range(100_000)) current, peak = tracemalloc.get_traced_memory() tracemalloc.stop()

Learn it in a lesson: Advanced Collections, itertools & functools · Counter & defaultdict · deque & Queues · itertools · Working with JSON · Dates & Times (datetime) · Modules and Packages · Randomness with the random Module · Regular Expressions (re) · Parallelism with concurrent.futures · Profiling & Optimising Python Performance · Memory Management & Garbage Collection Internals

Environment & Tooling

ConceptSyntaxExample
Create venv
Make an isolated environment so project deps don't clash.
python -m venv venvpython -m venv venv
Activate venv
On Windows: venv\Scripts\activate. Deactivate with `deactivate`.
source venv/bin/activatesource venv/bin/activate
Install package
Install a package from PyPI into the Python that runs pip: with a venv active, the venv's.
python -m pip install pkgpython -m pip install requests
Freeze deps
Write every installed package's exact version into a file, the packages they pulled in too.
python -m pip freeze > requirements.txtpython -m pip freeze > requirements.txt
Install from file
Install every dependency listed in a requirements file.
python -m pip install -r requirements.txtpython -m pip install -r requirements.txt
Check installs
List installed packages whose requirements aren't met; exit status 1 if there are any.
python -m pip checkpython -m pip check
Run a module
Run a library module as a script (e.g. a quick web server).
python -m modulepython -m http.server 8000

Learn it in a lesson: Virtual Environments & Dependency Management Best Practices · Module & Package Architecture for Large Codebases

Logging & Debugging

ConceptSyntaxExample
Logger
One logger per module, named after it. Give values as arguments: they're filled in only for lines that are shown.
logging.getLogger(__name__)log = logging.getLogger(__name__) log.info("order %s paid", order_id)
Configure logging
Once, at the program's start; a second call changes nothing unless it passes force=True.
logging.basicConfig(level=logging.INFO)logging.basicConfig(level=logging.INFO)
Log an error
Inside except: an ERROR line, then the traceback.
log.exception("msg")try: charge(5000) except ValueError: log.exception("charge failed")
Debugger
Stops the program in pdb, in a terminal; PYTHONBREAKPOINT=0 turns every breakpoint() off.
breakpoint()breakpoint()

Learn it in a lesson: Logging, Debugging & Error Handling at Scale