Quick Reference Print-friendly • Last-minute revision

Python Cheatsheet 🐍

Essential Python syntax, data structures, and patterns for quick revision before interviews.

📦 Data Types & Structures

# Mutable: list, dict, set
# Immutable: int, float, str, tuple, frozenset

# List comprehension
squares = [x**2 for x in range(10) if x % 2 == 0]

# Dict comprehension
word_len = {w: len(w) for w in ["hello", "world"]}

# Set operations
a = {1, 2, 3}; b = {2, 3, 4}
a | b  # Union: {1, 2, 3, 4}
a & b  # Intersection: {2, 3}
a - b  # Difference: {1}

# Collections
from collections import Counter, defaultdict, deque, namedtuple
Counter("hello")  # {'l': 2, 'h': 1, 'e': 1, 'o': 1}
dd = defaultdict(list)  # Default value for missing keys

⚡ Functions & Decorators

# Lambda
add = lambda x, y: x + y

# *args, **kwargs
def func(*args, **kwargs): pass

# Decorator pattern
from functools import wraps
def decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result
    return wrapper

# Generator — yields values lazily
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# Context Manager
from contextlib import contextmanager
@contextmanager
def timer():
    import time; start = time.time()
    yield
    print(f"Elapsed: {time.time() - start:.2f}s")

🏗️ OOP Quick Reference

# Class essentials
class Model:
    count = 0

    def __init__(self, name):
        self.name = name
        Model.count += 1

    def __repr__(self):
        return f"Model({self.name})"

    @classmethod
    def from_config(cls, config):
        return cls(config['name'])

    @staticmethod
    def validate(x): return x > 0

    @property
    def info(self):
        return f"{self.name} (#{Model.count})"

# Abstract Base Class
from abc import ABC, abstractmethod
class Pipeline(ABC):
    @abstractmethod
    def run(self): pass

# Dataclass
from dataclasses import dataclass
@dataclass
class Point:
    x: float
    y: float

🎯 Interview Patterns

# Sorting with key
sorted(items, key=lambda x: x.score, reverse=True)

# Two pointers
left, right = 0, len(arr) - 1
while left < right:
    if condition: left += 1
    else: right -= 1

# Sliding window
from collections import deque
window = deque(maxlen=k)

# Binary search
import bisect
pos = bisect.bisect_left(sorted_arr, target)

# Enumerate + zip
for i, (a, b) in enumerate(zip(list1, list2)):
    pass

# Exception handling
try:
    result = risky_operation()
except (TypeError, ValueError) as e:
    handle(e)
else:
    process(result)  # runs only if no exception
finally:
    cleanup()

# Walrus operator (3.8+)
if (n := len(data)) > 10:
    print(f"Large: {n} items")

🔑 Must-Know Facts

Concept Answer
Mutable typeslist, dict, set, bytearray
Immutable typesint, float, str, tuple, frozenset, bytes
Falsy values0, 0.0, "", [], , (), None, False
== vs is== checks value; is checks identity (same object)
GILAllows only 1 thread to run Python bytecode at a time
Shallow copycopy() or [:] — nested objects still shared
Deep copycopy.deepcopy() — fully independent
LEGB ruleLocal → Enclosing → Global → Built-in