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

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}

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)]

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

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'

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]

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)

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')

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 if no error; finally always runs (cleanup).
try: ... else: ... finally: ...try: f = open('x') finally: f.close()
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

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
Return every line of the file as a list of strings.
f.readlines()lines = open('a.txt').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()

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; first arg is always self.
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})'
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

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]))

Standard Library

ConceptSyntaxExample
Counter
Count occurrences of items quickly; .most_common() ranks them.
from collections import CounterCounter('aabbbc') # {'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')
math / random
Math functions and random number generation from the std lib.
import math, randommath.sqrt(16); random.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']

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
Download and install a package from PyPI into your environment.
pip install pkgpip install requests
Freeze deps
Record exact installed versions so others can reproduce them.
pip freeze > requirements.txtpip freeze > requirements.txt
Install from file
Install every dependency listed in a requirements file.
pip install -r requirements.txtpip install -r requirements.txt
Run a module
Run a library module as a script (e.g. a quick web server).
python -m modulepython -m http.server 8000