🐍 Python Cheat Sheet
Modern Python 3 — types, OOP, async, type hints and common patterns.
📦 Types & Variables
Basic types
x: int = 42 y: float = 3.14 b: bool = True # True / False s: str = "hello" n: None = None type(x) # <class 'int'> isinstance(x, int) # True
Multiple assignment & unpacking
a, b = 1, 2 a, b = b, a # swap first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4] x = y = z = 0 # chain assign
Numeric operations
10 / 3 # 3.333... (true division) 10 // 3 # 3 (floor division) 10 % 3 # 1 (modulo) 2 ** 10 # 1024 (power) abs(-5) # 5 round(3.567, 2) # 3.57
🔤 Strings
f-strings & formatting
name = "Feem"
age = 30
msg = f"Hello {name}, age {age}"
msg = f"{3.14159:.2f}" # "3.14"
msg = f"{1000000:,}" # "1,000,000"
msg = f"{'left':<10}" # left-align in 10 charsCommon string methods
s = " Hello World "
s.strip() # "Hello World"
s.lower() / s.upper()
s.split(" ") # ["Hello", "World"]
",".join(["a","b"]) # "a,b"
s.replace("o","0")
s.startswith("H")
s.find("World") # index or -1
s.count("l") # 3
s[0:5] # "Hello" (slice)Multiline & raw strings
multi = """ line one line two """ raw = r"C:\Users\no\escape" # raw string
📋 Lists & Tuples
List operations
lst = [1, 2, 3] lst.append(4) lst.extend([5, 6]) lst.insert(0, 0) lst.remove(3) # remove first 3 lst.pop() # remove & return last lst.pop(0) # remove at index lst.sort() lst.sort(reverse=True) sorted(lst) # returns new sorted list lst.reverse() lst.index(2) # first occurrence lst.count(2) len(lst)
Slicing
lst[1:3] # [2, 3] lst[::-1] # reversed lst[::2] # every other element lst[-1] # last element lst[-2:] # last two
Tuples (immutable)
t = (1, 2, 3) t = 1, 2, 3 # parens optional single = (1,) # trailing comma for single-item a, b, c = t # unpack
🗃️ Dicts & Sets
Dict operations
d = {"a": 1, "b": 2}
d["c"] = 3
d.get("x", 0) # 0 if missing
d.keys() / d.values() / d.items()
d.update({"d": 4})
d.pop("a")
"a" in d # True
del d["b"]
# Merge (Python 3.9+)
merged = d1 | d2
d1 |= d2defaultdict & Counter
from collections import defaultdict, Counter
dd = defaultdict(int)
dd["missing"] += 1 # no KeyError
words = ["a", "b", "a", "c", "a"]
c = Counter(words)
c.most_common(2) # [("a",3), ("b",1)]Sets
s = {1, 2, 3}
s.add(4)
s.remove(1)
s.discard(99) # no error if missing
s1 | s2 # union
s1 & s2 # intersection
s1 - s2 # difference
s1 ^ s2 # symmetric difference🔀 Control Flow
if / elif / else
if x > 0:
print("positive")
elif x < 0:
print("negative")
else:
print("zero")
# Ternary
result = "yes" if x > 0 else "no"for & while loops
for i in range(5): # 0..4
print(i)
for i in range(2, 10, 2): # 2,4,6,8
pass
for i, v in enumerate(lst): # index + value
print(i, v)
for k, v in d.items():
print(k, v)
# while
while n < 100:
n *= 2match (Python 3.10+)
match command:
case "quit":
quit()
case "go" | "run":
run()
case {"action": action, "value": val}:
handle(action, val)
case _:
print("unknown")🔧 Functions
Function basics
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
greet("Feem") # positional
greet(name="Feem") # keyword
greet("Feem", "Hi")*args and **kwargs
def log(*args, **kwargs):
print(args) # tuple
print(kwargs) # dict
log(1, 2, key="val")
# Unpack
nums = [1, 2, 3]
func(*nums) # spread list
func(**{"a": 1, "b": 2}) # spread dictLambda & higher-order
square = lambda x: x ** 2 lst = [3, 1, 2] sorted(lst, key=lambda x: -x) # [3,2,1] from functools import reduce total = reduce(lambda a,b: a+b, [1,2,3]) # 6 list(map(square, [1,2,3])) # [1,4,9] list(filter(lambda x: x>1, [1,2,3])) # [2,3]
Decorators
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__}: {time.time()-start:.3f}s")
return result
return wrapper
@timer
def slow(): time.sleep(1)🏗️ Classes & OOP
Class definition
class Animal:
species = "Unknown" # class variable
def __init__(self, name: str, age: int):
self.name = name # instance variable
self.age = age
def speak(self) -> str:
return f"{self.name} speaks"
def __repr__(self) -> str:
return f"Animal({self.name!r})"
def __str__(self) -> str:
return self.name
@classmethod
def create(cls, name): return cls(name, 0)
@staticmethod
def info(): return "This is an animal"
@property
def summary(self): return f"{self.name}/{self.age}"Inheritance
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def speak(self) -> str: # override
return "Woof!"
d = Dog("Rex", 3, "Lab")
isinstance(d, Animal) # Truedataclass (Python 3.7+)
from dataclasses import dataclass, field
@dataclass
class User:
name: str
age: int = 0
tags: list = field(default_factory=list)
def greet(self): return f"Hi {self.name}"
u = User("Feem", 30)
# __init__, __repr__, __eq__ auto-generated⚡ Comprehensions
List / dict / set / generator
# List
squares = [x**2 for x in range(10) if x % 2 == 0]
# Dict
d = {k: v for k, v in pairs if v}
# Set
unique = {x.lower() for x in words}
# Generator (lazy — no brackets, use ())
gen = (x**2 for x in range(1_000_000))
next(gen) # evaluate one at a timezip, enumerate, any/all
list(zip([1,2,3], ["a","b","c"])) # [(1,"a"), (2,"b"), (3,"c")] list(enumerate(["a","b"], start=1)) # [(1,"a"), (2,"b")] any(x > 0 for x in lst) # True if any all(x > 0 for x in lst) # True if all
⚠️ Exceptions
try / except / finally
try:
result = 10 / x
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError):
print("type or value error")
else:
print("success:", result) # runs if no exception
finally:
print("always runs")Custom exceptions & raise
class AppError(Exception):
def __init__(self, msg: str, code: int = 0):
super().__init__(msg)
self.code = code
raise AppError("not found", 404)
# Re-raise
try:
risky()
except Exception as e:
log(e)
raise # re-raise same exception📂 Files & IO
Read & write files
with open("file.txt", "r") as f:
content = f.read()
lines = f.readlines()
with open("out.txt", "w") as f:
f.write("Hello\n")
f.writelines(["a\n","b\n"])
# append mode
with open("log.txt", "a") as f:
f.write("new line\n")JSON & pathlib
import json
from pathlib import Path
data = json.loads('{"key": 1}')
json.dumps(data, indent=2)
p = Path("data/config.json")
p.read_text()
p.write_text("{}")
p.exists()
p.parent / "other.json" # path join⚡ Async / Await
async functions
import asyncio
async def fetch(url: str) -> str:
await asyncio.sleep(1) # simulate IO
return f"data from {url}"
asyncio.run(fetch("http://example.com"))gather & tasks
async def main():
# Run concurrently
results = await asyncio.gather(
fetch("url1"),
fetch("url2"),
fetch("url3"),
)
# Task
task = asyncio.create_task(fetch("url"))
await task🏷️ Type Hints
Common type annotations
from typing import Optional, Union, Any
from collections.abc import Callable, Iterator
x: int | None = None # Python 3.10+
x: Optional[int] = None # equivalent
def f(a: list[int], b: dict[str, Any]) -> None: ...
Callback = Callable[[int, str], bool]
def apply(fn: Callback, n: int) -> bool:
return fn(n, "test")TypedDict & Protocol
from typing import TypedDict, Protocol
class UserDict(TypedDict):
name: str
age: int
class Drawable(Protocol):
def draw(self) -> None: ...
# Generic type alias (Python 3.12)
type Vector[T] = list[T]