Python Cheat Sheet

A quick reference for Python syntax, built-in functions, and data structures.

Data Structures

Listfruits = ['apple', 'banana', 'cherry']
Tuplepoint = (10, 20) (immutable)
Setunique = {1, 2, 3} (no duplicates)
Dictuser = {'name': 'John', 'age': 30}
List comprehension[x**2 for x in range(10) if x % 2 == 0]
Dict comprehension{k: v for k, v in zip(keys, values)}
Slicingarr[1:4] — indices 1, 2, 3; arr[::-1] — reversed

Functions & Control

Functiondef greet(name: str) -> str: return f'Hello {name}'
Lambdalambda x: x * 2
*argsdef fn(*args): # variable positional args
**kwargsdef fn(**kwargs): # variable keyword args
Decorator@staticmethod / @classmethod / @property
Context managerwith open('file.txt') as f:

Common Stdlib Modules

osos.path.join(), os.environ, os.listdir()
jsonjson.loads(), json.dumps(), json.dump()
rere.search(), re.match(), re.findall(), re.sub()
datetimedatetime.now(), date.today(), timedelta
pathlibPath('dir/file.txt').read_text(), .write_text()
collectionsdefaultdict, Counter, namedtuple, deque