# Iteratefor key, value in d.items():
print(f"{key}: {value}")
# Dict comprehension
squares = {x: x**2for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Sets & Tuples
# Sets — unordered, unique values
s = {1, 2, 3}
s.add(4) # add element
s.discard(2) # remove (no error if missing)
s.remove(3) # remove (KeyError if missing)# Set operations
a | b # union
a & b # intersection
a - b # difference
a ^ b # symmetric difference
a.issubset(b) # True if a ⊆ b# Tuples — immutable, ordered
t = (1, 2, 3)
t[0] # 1
a, b, c = t # unpacking
single = (1,) # single-element tuple (note comma)
Control Flow
# If / elif / elseif x > 10:
print("big")
elif x > 5:
print("medium")
else:
print("small")
# Ternary
result = "yes"if condition else"no"# For loopfor i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)
for i, val in enumerate(lst): # index + value
print(i, val)
for a, b in zip(list1, list2): # parallel iteration
print(a, b)
# While loopwhile count < 10:
count += 1# break, continue, elsefor x in lst:
if x == target:
breakelse:
print("not found") # runs if no break# Match (Python 3.10+)match command:
case"start":
start()
case"stop":
stop()
case _:
print("unknown")
Functions
# Basic functiondef greet(name):
return f"Hello, {name}!"# Default parametersdef greet(name="World"):
return f"Hello, {name}!"# *args and **kwargsdef func(*args, **kwargs):
print(args) # tuple of positional args
print(kwargs) # dict of keyword args# Lambda (anonymous function)
square = lambda x: x ** 2
sorted(lst, key=lambda x: x[1])
# Type hintsdef add(a: int, b: int) -> int:
return a + b
# Decoratorsdef timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Took {time.time() - start:.2f}s")
return result
return wrapper
@timer
def slow_fn():
time.sleep(1)
# Generatordef count_up(n):
i = 0while i < n:
yield i
i += 1
# Read filewith open("file.txt", "r") as f:
content = f.read() # entire file as string
lines = f.readlines() # list of lines# Read line by line (memory efficient)with open("file.txt") as f:
for line in f:
print(line.strip())
# Write filewith open("file.txt", "w") as f:
f.write("Hello\n")
# Append to filewith open("file.txt", "a") as f:
f.write("More text\n")
# JSONimport json
data = json.loads(json_string) # parse JSON string
json_str = json.dumps(data, indent=2) # to JSON stringwith open("data.json") as f:
data = json.load(f) # read JSON filewith open("data.json", "w") as f:
json.dump(data, f, indent=2) # write JSON file# CSVimport csv
with open("data.csv") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"])
Mode
Description
"r"
Read (default)
"w"
Write (overwrites)
"a"
Append
"x"
Create (error if exists)
"rb" / "wb"
Binary read/write
Comprehensions
# List comprehension
squares = [x**2for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# Dict comprehension
d = {k: v for k, v in zip(keys, values)}
# Set comprehension
unique = {x.lower() for x in words}
# Generator expression (lazy, memory efficient)
total = sum(x**2for x in range(1000000))
# Nested comprehension
flat = [x for row in matrix for x in row]
# Conditional expression
labels = ["even"if x%2==0else"odd"for x in range(5)]
Error Handling
try:
result = 10 / 0except ZeroDivisionError:
print("Cannot divide by zero")
except (TypeError, ValueError) as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected: {e}")
else:
print("Success") # runs if no exceptionfinally:
print("Cleanup") # always runs# Raise exceptionraise ValueError("Invalid input")
# Custom exceptionclass AppError(Exception):
pass
Exception
When
ValueError
Wrong value (e.g., int("abc"))
TypeError
Wrong type (e.g., "a" + 1)
KeyError
Missing dict key
IndexError
Index out of range
FileNotFoundError
File doesn't exist
AttributeError
Missing attribute/method
ImportError
Module not found
ZeroDivisionError
Division by zero
StopIteration
Iterator exhausted
Standard Library Highlights
# os / pathlib — file systemfrom pathlib import Path
p = Path("dir/file.txt")
p.exists() p.is_file() p.is_dir()
p.read_text() p.write_text("data")
p.parent p.stem p.suffix p.name
list(Path(".").glob("*.py"))
# datetimefrom datetime import datetime, timedelta
now = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M")
parsed = datetime.strptime("2026-05-08", "%Y-%m-%d")
tomorrow = now + timedelta(days=1)
# collectionsfrom collections import Counter, defaultdict, deque
Counter(["a","b","a"]) # Counter({'a': 2, 'b': 1})
dd = defaultdict(list)
dd["key"].append(1) # auto-creates list# itertoolsfrom itertools import chain, product, combinations
list(chain([1,2], [3,4])) # [1, 2, 3, 4]
list(combinations("abc", 2)) # [('a','b'), ('a','c'), ('b','c')]# re — regeximport re
re.findall(r'\d+', "abc 123") # ['123']
re.sub(r'\s+', ' ', text) # collapse whitespace# randomimport random
random.randint(1, 10) # random int 1-10
random.choice(lst) # random element
random.shuffle(lst) # shuffle in place
random.sample(lst, 3) # 3 random elements