Python Cheatsheet
Every essential Python pattern: data structures, strings, control flow, comprehensions, functions, file I/O, and error handling, with syntax and real use cases.114 commands · 7 sections
Python is the language of scripts, automation, and data work. This cheatsheet covers the patterns you write daily: data types and structures, strings and f-strings, control flow, comprehensions, functions and lambdas, file I/O with context managers, and modules with error handling.
Every entry shows real syntax followed by the use case: when and why you reach for it.
Data Types & Structures28
x: int = 42x: str = "hello"x: float = 3.14x: bool = Truelst: list[int] = [1, 2, 3]tup: tuple[int, str] = (1, "a")d: dict[str, int] = {"a": 1}s: set[int] = {1, 2, 3}lst.append(x)lst.extend([x, y])lst.insert(0, x)lst.pop()lst.pop(0)lst.remove(x)x in lstlst.index(x)lst.sort()sorted(lst, reverse=True)lst[::-1]d.get(key, default)d.setdefault(key, [])d.keys() / d.values() / d.items()collections.Counter(lst)collections.defaultdict(list)collections.deque(maxlen=10)enumerate(lst)zip(a, b)isinstance(x, int)Strings & f-strings17
s.upper() / s.lower()s.strip()s.split(",")",".join(lst)s.replace(old, new)s.startswith("https")s.endswith(".json")s.find("x")"x" in ss[:10]f"{name} is {age} years old"f"{x:.2f}"f"{x:>10}"f"{x:,}""%s" % values.title()s.isdigit()Control Flow & Loops9
if x > 0: ... elif x == 0: ... else: ...for x in iterable:for i in range(10):while condition:breakcontinuefor x in items:
if cond: break
else:match value:
case 1: ...
case _: ...a if cond else bComprehensions8
[x * 2 for x in range(10)][x for x in items if x > 0]{x: x**2 for x in range(5)}{x.upper() for x in words}(x for x in items if x > 0)[[y for y in range(x)] for x in range(3)][f(x) for x in items if g(x)]sum(x for x in nums)Functions & Lambdas19
def greet(name: str) -> str:
return f"Hi {name}"def f(a, b=10):def f(*args):def f(**kwargs):lambda x: x * 2sorted(items, key=len)map(f, items)filter(f, items)functools.reduce(f, items)return a, bfunctools.lru_cache(maxsize=128)def outer():
def inner(): ...@decorator
def f():def decorator(fn):
def wrapper(*a, **kw): ...def gen():
yield xnext(gen)from dataclasses import dataclass
@dataclass
class User:from typing import Optional, Union, Literalfrom typing import TypeVar, GenericFile I/O & Context Managers16
with open("f.txt") as f:
data = f.read()with open("f.txt", "w") as f:
f.write("hello")with open("f.txt", "a") as f:for line in f:pathlib.Path("dir")p.exists() / p.is_file()p.mkdir(parents=True, exist_ok=True)p.read_text() / p.write_text("x")Path("dir").glob("*.txt")Path("f").unlink()Path("f").rename("new")json.dump(obj, f)json.load(f)from contextlib import contextmanagerimport csv
csv.DictReader(f)import shutil
shutil.copy(src, dst)Modules & Error Handling17
import os
os.environ.get("KEY")import sys
sys.exit(1)import argparseimport subprocess
subprocess.run(["ls", "-la"], check=True)import re
re.search(r"\d+", s)import requests
requests.get(url, timeout=10)import time
time.sleep(1)try:
risky()
except ValueError as e:try:
...
except (TypeError, ValueError):try:
...
finally:try:
...
except Exception as e:
log(e)
else:raise ValueError("bad input")raise ... from eclass MyError(Exception):
passimport logging
logging.basicConfig(level=logging.INFO)import json
json.dumps(obj, indent=2)from collections import OrderedDictPython Cheatsheet
Every essential Python pattern: data structures, strings, control flow, comprehensions, functions, file I/O, and error handling, with syntax and real use cases.
Python is the language of scripts, automation, and data work. This cheatsheet covers the patterns you write daily: data types and structures, strings and f-strings, control flow, comprehensions, functions and lambdas, file I/O with context managers, and modules with error handling.
Every entry shows real syntax followed by the use case: when and why you reach for it.
Data Types & Structures
x: int = 42: Type annotation: declare an integer variable.x: str = "hello": Type-annotated string.x: float = 3.14: Type-annotated float.x: bool = True: Type-annotated boolean.lst: list[int] = [1, 2, 3]: A list: ordered, mutable collection.tup: tuple[int, str] = (1, "a"): A tuple: immutable, fixed-size collection.d: dict[str, int] = {"a": 1}: A dictionary: key-value mapping.s: set[int] = {1, 2, 3}: A set: unique, unordered values.lst.append(x): Add an item to the end of a list.lst.extend([x, y]): Add multiple items to a list.lst.insert(0, x): Insert an item at a specific index.lst.pop(): Remove and return the last item: LIFO stack behavior.lst.pop(0): Remove and return the first item: FIFO queue behavior.lst.remove(x): Remove the first occurrence of a value.x in lst: Membership check: is this in the list?lst.index(x): Find the index of a value.lst.sort(): Sort a list in place.sorted(lst, reverse=True): Return a new sorted list, descending.lst[::-1]: Reverse a list with slicing: the Python idiom.d.get(key, default): Read a dict key with a fallback: no KeyError.d.setdefault(key, []): Get a key, creating it with a default if missing: group-by pattern.d.keys() / d.values() / d.items(): Iterate over keys, values, or pairs.collections.Counter(lst): Count occurrences: frequency analysis.collections.defaultdict(list): Dict that auto-creates missing values: group-by without setdefault.collections.deque(maxlen=10): Fast append/pop at BOTH ends with bounded size: rolling windows.enumerate(lst): Loop with an index: the Pythonic counter.zip(a, b): Pair up two iterables.isinstance(x, int): Type check at runtime.Strings & f-strings
s.upper() / s.lower(): Case conversion.s.strip(): Remove surrounding whitespace: clean user input.s.split(","): Split into a list by delimiter.",".join(lst): Join a list into a string.s.replace(old, new): Replace all occurrences.s.startswith("https"): Prefix check.s.endswith(".json"): Suffix check.s.find("x"): Index of a substring, or -1 if missing."x" in s: Substring membership.s[:10]: Slice: first 10 characters.f"{name} is {age} years old": f-string interpolation: the modern way to build strings.f"{x:.2f}": Format a float to 2 decimal places.f"{x:>10}": Right-align in 10 characters: aligned table output.f"{x:,}": Thousands separator: readable large numbers."%s" % value: Old-style formatting: seen in legacy code, avoid in new code.s.title(): Title case: "hello world" becomes "Hello World".s.isdigit(): Check if the string is all digits: validate input.Control Flow & Loops
if x > 0: ... elif x == 0: ... else: ...: Conditional branching.for x in iterable:: Iterate over any iterable.for i in range(10):: Loop a fixed number of times.while condition:: Loop until a condition is false.break: Exit the loop immediately.continue: Skip to the next iteration.for x in items:
if cond: break
else:: Loop else: runs only when the loop completed without break.match value:
case 1: ...
case _: ...: Structural pattern matching (Python 3.10+): switch with unpacking.a if cond else b: Ternary expression: inline conditional.Comprehensions
[x * 2 for x in range(10)]: List comprehension: build a list in one line.[x for x in items if x > 0]: List comprehension with filter.{x: x**2 for x in range(5)}: Dict comprehension.{x.upper() for x in words}: Set comprehension: deduplicate while transforming.(x for x in items if x > 0): Generator expression: lazy, memory-friendly for large data.[[y for y in range(x)] for x in range(3)]: Nested comprehension: grids and matrices.[f(x) for x in items if g(x)]: Transform AND filter in one pass.sum(x for x in nums): Sum a stream: generator keeps memory flat.Functions & Lambdas
def greet(name: str) -> str:
return f"Hi {name}": Define a typed function.def f(a, b=10):: Default parameter value: optional arguments.def f(*args):: Variable positional arguments.def f(**kwargs):: Variable keyword arguments: config bags.lambda x: x * 2: Anonymous function: inline logic for sort/map/filter.sorted(items, key=len): Sort by a custom key function.map(f, items): Apply a function to every item (lazy).filter(f, items): Keep items where the function is true.functools.reduce(f, items): Fold a sequence into one value.return a, b: Return multiple values as a tuple.functools.lru_cache(maxsize=128): Memoize a function: cache expensive computations.def outer():
def inner(): ...: Nested function: closures for counters and decorators.@decorator
def f():: Wrap a function with a decorator: logging, timing, auth.def decorator(fn):
def wrapper(*a, **kw): ...: Write a decorator: the wrapper pattern.def gen():
yield x: Generator function: lazy sequences.next(gen): Pull the next value from a generator/iterator.from dataclasses import dataclass
@dataclass
class User:: Dataclass: boilerplate-free data containers.from typing import Optional, Union, Literal: Rich type hints: Optional[str], Union[int, str], Literal["a", "b"].from typing import TypeVar, Generic: Generics: type-safe containers.File I/O & Context Managers
with open("f.txt") as f:
data = f.read(): Read a whole file: the context manager closes it automatically.with open("f.txt", "w") as f:
f.write("hello"): Write a file (overwrites).with open("f.txt", "a") as f:: Append to a file: log lines.for line in f:: Iterate a file line by line: memory-safe for huge files.pathlib.Path("dir"): Modern path handling: cross-platform, chainable.p.exists() / p.is_file(): Check a path exists and its type.p.mkdir(parents=True, exist_ok=True): Create directories recursively: no error if present.p.read_text() / p.write_text("x"): Read/write a text file via pathlib.Path("dir").glob("*.txt"): Glob files in a directory.Path("f").unlink(): Delete a file.Path("f").rename("new"): Rename or move a file.json.dump(obj, f): Serialize Python data to JSON.json.load(f): Parse JSON from a file.from contextlib import contextmanager: Build your own context manager for setup/teardown.import csv
csv.DictReader(f): Read CSV into dicts: headers become keys.import shutil
shutil.copy(src, dst): Copy files/directories with stdlib.Modules & Error Handling
import os
os.environ.get("KEY"): Read environment variables: config without code changes.import sys
sys.exit(1): Exit a script with a non-zero code: signal failure to CI.import argparse: Parse CLI arguments: professional scripts.import subprocess
subprocess.run(["ls", "-la"], check=True): Run shell commands from Python: automation glue.import re
re.search(r"\d+", s): Regex search: extract patterns.import requests
requests.get(url, timeout=10): HTTP requests (third-party, pip install requests).import time
time.sleep(1): Pause execution: retry loops and rate limiting.try:
risky()
except ValueError as e:: Catch a specific exception type.try:
...
except (TypeError, ValueError):: Catch multiple exception types together.try:
...
finally:: Always-run cleanup: close connections, release locks.try:
...
except Exception as e:
log(e)
else:: else runs only on success: keep try blocks small.raise ValueError("bad input"): Raise an exception with a message.raise ... from e: Chain exceptions: keep the original traceback.class MyError(Exception):
pass: Define a custom exception type.import logging
logging.basicConfig(level=logging.INFO): Structured logging: better than print for real apps.import json
json.dumps(obj, indent=2): Pretty-print JSON: debug data structures.from collections import OrderedDict: Dict with guaranteed insertion order (dicts are ordered since 3.7 anyway).Frequently asked questions
What is the difference between a list and a tuple?
Lists are mutable: you can add, remove, and change elements. Tuples are immutable and hashable, so they work as dictionary keys. Use tuples for fixed data and lists for collections that change.
How does a list comprehension work?
It builds a new list in one expression: [f(x) for x in iterable if condition]. For example [x*2 for x in range(10) if x % 2 == 0] yields even numbers doubled. They are faster and more readable than manual loops.
What is the difference between a generator and a list?
A generator yields items one at a time and never stores the whole sequence in memory: ideal for large or infinite data. A list holds everything eagerly. Use generators for streaming and lists for random access.
How do I handle exceptions properly?
Use try/except/else/finally: put risky code in try, handle specific exceptions in except, run success-only code in else, and always-run cleanup in finally. Catch specific exception types, never bare except.