Python Cheatsheet
Modern Python — data types, control flow, comprehensions, functions, modules, and file I/O.
Python is the go-to language for data science, automation, backend development, and scripting. This cheatsheet covers Python 3.11+ syntax including data structures, comprehensions, f-strings, type hints, and context managers.
All examples assume Python 3.10+ with modern typing support.
Data Types & Structures
x = 42 # intmy_list = [1, 2, 3]my_dict = {"key": "value"}my_set = {1, 2, 3}from typing import Optionalclass MyClass:@dataclassStrings & f-strings
f"Hello {name}, age {age}"" ".join(["a", "b", "c"])"hello world".split()Control Flow & Loops
if/elif/elsefor item in iterable:while condition:match value:Comprehensions
[x**2 for x in range(10)]{k: v for k, v in pairs}{x for x in items if x > 0}Functions & Lambdas
def func(param: type) -> return_type:lambda x: x * 2def func(*args, **kwargs):File I/O & Context Managers
with open("file.txt") as f:open("file.txt", "w") as f:Modules & Error Handling
import moduletry/except/finallyraise ValueError("msg")Python Cheatsheet
Modern Python — data types, control flow, comprehensions, functions, modules, and file I/O.
Python is the go-to language for data science, automation, backend development, and scripting. This cheatsheet covers Python 3.11+ syntax including data structures, comprehensions, f-strings, type hints, and context managers.
All examples assume Python 3.10+ with modern typing support.
Data Types & Structures
x = 42 # int — Python is dynamically typed. Variables are assigned without type declarations.my_list = [1, 2, 3] — A list is an ordered, mutable collection. Supports mixed types.my_dict = {"key": "value"} — A dict stores key-value pairs. Keys must be hashable (strings, numbers, tuples).my_set = {1, 2, 3} — A set is an unordered collection of unique elements. Great for membership tests.from typing import Optional — Type hints for better IDE support and static analysis. No runtime effect.class MyClass: — Define a class. Modern Python uses __init__ for constructor.@dataclass — Auto-generate __init__, __repr__, __eq__ for data-holding classes.Strings & f-strings
f"Hello {name}, age {age}" — f-strings — embed expressions in string literals with {}." ".join(["a", "b", "c"]) — Join a list of strings into a single string with a separator."hello world".split() — Split a string on whitespace (default) or a delimiter.Control Flow & Loops
if/elif/else — Conditional branching with elif (not else if or elsif).for item in iterable: — Iterate over any iterable (list, tuple, dict, string, file).while condition: — Repeat while condition is True. Use break to exit early.match value: — Structural pattern matching (Python 3.10+). Like switch but more powerful.Comprehensions
[x**2 for x in range(10)] — List comprehension — concise way to build lists from iterables.{k: v for k, v in pairs} — Dict comprehension — build dictionaries from key-value pairs.{x for x in items if x > 0} — Set comprehension — build sets with filtering.Functions & Lambdas
def func(param: type) -> return_type: — Define a function with optional type annotations.lambda x: x * 2 — Anonymous inline function. Often used with map, filter, sorted.def func(*args, **kwargs): — *args captures positional excess, **kwargs captures keyword excess.File I/O & Context Managers
with open("file.txt") as f: — Context manager for safe file handling. Auto-closes on block exit.open("file.txt", "w") as f: — Open a file in write mode ("w"), append ("a"), or read ("r", default).Modules & Error Handling
import module — Import a module. Use from x import y for specific names.try/except/finally — Catch and handle exceptions. Finally always runs.raise ValueError("msg") — Manually raise an exception with a descriptive message.