Skip to the content.

Python Cheatsheet

Python Cheatsheet

A quick reference guide for modern Python (3.10+), covering core syntax, built-in structures, OOP, error handling, and common idiomatic design patterns.

Control Flow & Core Syntax

# Variables and basic types (dynamically typed)
x = 10                  # int
y = 3.14                # float
name = "Alice"          # str
is_valid = True         # bool

# Conditional branches
if x > 10:
    print("Greater than 10")
elif x == 10:
    print("Exactly 10")
else:
    print("Less than 10")

# Structural Pattern Matching (Python 3.10+)
match x:
    case 1 | 2:
        print("One or Two")
    case 10:
        print("Ten")
    case _:
        print("Default match")

Built-in Data Structures

# 1. Lists (Ordered, mutable, duplicates allowed)
nums = [1, 2, 3, 4]
nums.append(5)          # Add to end: [1, 2, 3, 4, 5]
nums.pop()              # Remove last: [1, 2, 3, 4]
first = nums[0]         # Index access
subset = nums[1:3]      # Slicing (exclusive end): [2, 3]
reversed_nums = nums[::-1] # Slicing trick to reverse: [4, 3, 2, 1]

# List Comprehensions (Idiomatic list generation)
squares = [n**2 for n in nums if n % 2 == 0] # [4, 16]

# 2. Dictionaries (Key-Value, ordered insertion since 3.7)
user = {"name": "Alice", "age": 30}
user["email"] = "a@b.com"
age = user.get("age", 25) # Safe retrieval with fallback default value

# Dictionary Comprehensions
squared_dict = {n: n**2 for n in nums} # {1: 1, 2: 4, 3: 9, 4: 16}

# 3. Sets (Unordered, mutable, unique elements only)
unique_names = {"Alice", "Bob", "Alice"} # {"Alice", "Bob"}
unique_names.add("Charlie")

# 4. Tuples (Ordered, immutable, duplicates allowed)
point = (10, 20)
x, y = point            # Unpacking tuple

Functions & Type Hinting

# Function with default arguments and type hints (Python 3.5+)
def greet(name: str, greeting: str = "Hello") -> str:
    """Greets a user with a message. (Docstring)"""
    return f"{greeting}, {name}!"

# Keyword-only arguments (forces named calls after '*')
def configure(*, host: str, port: int):
    pass
configure(host="localhost", port=8080) # configure("localhost", 8080) throws error

# Lambda Functions (Anonymous one-liners)
multiply = lambda a, b: a * b
result = multiply(3, 4) # 12

Object-Oriented Programming (Classes)

class Animal:
    # Class-level variable (shared across instances)
    species = "Mammal"

    def __init__(self, name: str, age: int):
        self.name = name        # Instance-level variable
        self._age = age         # Intended as protected (convention)
        self.__id = 123         # Private (triggers name mangling)

    # Instance method
    def speak(self) -> str:
        return "Generic Sound"

    # Property decorator (getter/setter)
    @property
    def age(self) -> int:
        return self._age

    @age.setter
    def age(self, value: int):
        if value >= 0:
            self._age = value

    # Dunder/Magic method (String representation)
    def __str__(self) -> str:
        return f"{self.name} is {self._age} years old"

# Inheritance
class Dog(Animal):
    def speak(self) -> str:
        return "Woof!"          # Method overriding

Error & Exception Handling

try:
    result = 10 / x
except ZeroDivisionError as e:
    print(f"Mathematical Error: {e}")
except TypeError as e:
    print(f"Type Mismatch: {e}")
else:
    print("Executed successfully if no errors occur")
finally:
    print("Always executed (for cleanup)")

# Raising custom exceptions
class ValidationError(Exception):
    """Custom validation exception class."""
    pass

if x < 0:
    raise ValidationError("Value cannot be negative.")

File I/O (Context Managers)

# Safe reading (closes file automatically even on error)
with open("data.txt", "r", encoding="utf-8") as file:
    content = file.read()       # Read entire file
    # lines = file.readlines()  # Read as list of lines

# Safe writing
with open("output.txt", "w", encoding="utf-8") as file:
    file.write("Hello World\n")

Idiomatic Pythonic Patterns

# 1. Enumerate (Index & Value tracking in loops)
names = ["Alice", "Bob", "Charlie"]
for idx, name in enumerate(names, start=1):
    print(f"{idx}: {name}")

# 2. Zip (Iterate multiple lists in parallel)
ages = [30, 25, 40]
for name, age in zip(names, ages):
    print(f"{name} is {age}")

# 3. Generators (Memory-efficient infinite streams or large listings)
def count_up_to(max_val):
    count = 1
    while count <= max_val:
        yield count             # Yields values lazily on-demand
        count += 1

# 4. Decorators (Modify or wrap function execution)
def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_decorator
def run():
    print("Running...")

Essential Standard Libraries

# 1. JSON handling
import json
data = {"name": "Bob", "active": True}
json_str = json.dumps(data)     # Serialize to string
parsed_obj = json.loads(json_str) # Deserialize to dictionary

# 2. Datetime manipulation
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")

# 3. Collections (Advanced data structures)
from collections import defaultdict, Counter
letter_counts = Counter("abracadabra") # Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
grouped_data = defaultdict(list)     # Safe append to uninitialized keys