Python Complete Cheat Sheet – Beginner to Advanced

🐍 Python Complete Cheat Sheet — Beginner to Advanced

The most useful Python reference in one place: syntax, data structures, OOP, libraries, and real-world patterns — built for students, self-learners, and developers.

📘 What This Page Covers

This single-page reference covers core Python from the very basics through advanced patterns, plus the libraries used most often in data analysis, web development, and automation. Every card is written to be scanned quickly, not read like a textbook.

🎓 Use it to prepare for interviews and exams, as a quick lookup while coding projects, or as a refresher before diving into a new library.

🔍 Use the search and filters below to jump straight to the topic, difficulty level, or use case you need.

All Core Control/Fn Data Struct Errors/Files OOP Modules Data Sci Web Dev Automation Advanced

⚡ Most Used Snippets at a Glance

squares = [x*x for x in range(10)]
d = {k: v for k, v in pairs}
def greet(name="World"):
    return f"Hello, {name}!"
class Dog:
    def __init__(self, name):
        self.name = name
import pandas as pd
df = pd.read_csv("data.csv")
df.head()
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.show()

No topics match your filters. Try clearing the search or selecting “All”.

🔵 Core Python — Beginner

🔢

Variables & Data Types

Beginner
  • x = 10, name = "Jagan", pi = 3.14
  • Core types: int, float, str, bool, None
  • Check type: type(x), isinstance(x, int)
  • Convert: int(), str(), float(), bool()
  • Multiple assign: a, b = 1, 2
x = 10
name = "Jagan"
pi = 3.14
is_valid = True
empty = None
a, b = 1, 2
⚠ Pitfalls:
  • Python is dynamically typed — variables can change type
  • bool(0), bool(""), bool([]) are all False
🎯 Use when: Use plain variables for simple values; convert types explicitly before math or concatenation.
⏱ 15-20 min⭐ Beginner

Operators

Beginner
  • Arithmetic: + - * / // % **
  • Comparison: == != > < >= <=
  • Logical: and, or, not
  • Membership: in, not in
  • Identity: is, is not
7 // 2   # 3 (floor div)
7 % 2    # 1 (modulo)
2 ** 5   # 32
"a" in "cat"     # True
x is None        # identity check
⚠ Pitfalls:
  • == compares values, is compares identity (object reference)
  • Chained comparisons work: 1 < x < 10
🎯 Use when: Use is only for None/singletons; use == for value comparison.
⏱ 15 min⭐ Beginner
🔤

Strings

Beginner
  • Slicing: s[0], s[-1], s[1:4], s[::-1]
  • f-strings: f"Hi {name}, {age+1}"
  • split(), join(), replace(), strip()
  • upper(), lower(), find(), startswith()
  • Strings are immutable sequences
s = "Hello World"
s[::-1]              # reversed
f"{s.upper()} - {len(s)}"
",".join(["a","b"])  # 'a,b'
"a,b,c".split(",")   # ['a','b','c']
⚠ Pitfalls:
  • Strings are immutable — every “modification” creates a new string
  • Use f-strings (3.6+) over % or .format() for readability
🎯 Use when: Use f-strings for formatting, .split()/.join() for parsing and building text.
⏱ 20-30 min⭐ Beginner
📋

Lists

Beginner
  • Create: lst = [1, 2, 3]
  • append(), extend(), insert(), pop(), remove()
  • Slicing: lst[1:3], lst[::-1]
  • Sort: lst.sort(), sorted(lst, key=..., reverse=True)
  • List comprehension: [x*x for x in lst if x>0]
lst = [1, 2, 3]
lst.append(4)
lst[1:3]          # [2, 3]
squares = [x*x for x in lst]
sorted(lst, reverse=True)
⚠ Pitfalls:
  • Mutable — passing a list to a function can change it in place
  • lst = lst2 copies the reference, not the data (use .copy())
🎯 Use when: Use lists for ordered, changeable collections of items.
⏱ 30-45 min⭐ Beginner
🔐

Tuples

Beginner
  • Create: t = (1, 2, 3) — immutable
  • Unpacking: x, y = (1, 2)
  • Single item needs comma: (1,)
  • Access like lists: t[0], t[-1]
  • Faster & hashable — usable as dict keys
point = (4, 5)
x, y = point
coords = {(0,0): "origin"}   # tuple as dict key
⚠ Pitfalls:
  • Forgetting the trailing comma for a 1-item tuple: (5) is just an int
  • Cannot append/remove items — tuples are immutable
🎯 Use when: Use tuples for fixed, immutable records (coordinates, RGB values, dict keys).
⏱ 10-15 min⭐ Beginner
🧩

Sets

Beginner
  • Create: s = {1, 2, 3} or set()
  • Unique elements only, unordered
  • union() / |, intersection() / &, difference() / -
  • add(), remove(), discard()
  • Fast membership testing with in
a = {1, 2, 3}
b = {2, 3, 4}
a | b   # {1,2,3,4}
a & b   # {2,3}
a - b   # {1}
⚠ Pitfalls:
  • {} creates an empty dict, not an empty set — use set()
  • Sets are unordered — no indexing allowed
🎯 Use when: Use sets to remove duplicates or perform fast membership checks and set algebra.
⏱ 15-20 min⭐ Beginner
🔑

Dictionaries

Beginner
  • Create: d = {"name": "Jagan", "age": 25}
  • keys(), values(), items()
  • Safe access: d.get("x", default)
  • Dict comprehension: {k: v*2 for k,v in d.items()}
  • Merge (3.9+): d1 | d2
d = {"name": "Jagan", "age": 25}
d.get("email", "N/A")
for k, v in d.items():
    print(k, v)
{k: v for k, v in d.items() if v}
⚠ Pitfalls:
  • d["missing"] raises KeyError — use .get() instead
  • Dicts keep insertion order since Python 3.7
🎯 Use when: Use dictionaries for fast key-based lookup and structured records (like JSON).
⏱ 25-35 min⭐ Beginner

🎲 Control Flow & Functions

🔀

Conditionals

Beginner
  • if / elif / else chains
  • Nested conditions for multi-factor logic
  • Ternary: x if cond else y
  • Truthy/falsy values control branching directly
  • 3.10+ pattern matching: match/case
age = 20
if age < 13:
    group = "child"
elif age < 20:
    group = "teen"
else:
    group = "adult"
label = "adult" if age >= 18 else "minor"
⚠ Pitfalls:
  • Do not confuse = (assignment) with == (comparison)
  • Watch indentation — Python uses whitespace, not braces
🎯 Use when: Use conditionals to branch logic based on data or user input.
⏱ 15-20 min⭐ Beginner
🔁

Loops

Beginner
  • for item in iterable:, while condition:
  • range(start, stop, step)
  • enumerate(lst) for index+value
  • zip(a, b) to loop in parallel
  • break, continue, pass
for i, name in enumerate(["a","b"]):
    print(i, name)
for x, y in zip([1,2],[3,4]):
    print(x+y)
while n > 0:
    n -= 1
⚠ Pitfalls:
  • Infinite loops if the while condition never becomes False
  • Modifying a list while iterating over it can skip elements
🎯 Use when: Use for for known sequences/iterables, while for condition-based repetition.
⏱ 20-30 min⭐ Beginner
ƒ

Functions

Beginner
  • def name(params): return value
  • Default args: def f(x, y=10):
  • Variadic: *args, **kwargs
  • Scope: local vs global (global keyword)
  • Type hints: def f(x: int) -> int:
def greet(name="World", *args, **kwargs):
    return f"Hello, {name}!"

def total(*nums):
    return sum(nums)
⚠ Pitfalls:
  • Never use a mutable default argument like def f(x=[])
  • Variables assigned inside a function are local unless declared global
🎯 Use when: Wrap reusable logic in functions; use *args/**kwargs for flexible APIs.
⏱ 30-45 min⭐ Beginner
λ

Lambda & Built-ins

Intermediate
  • lambda x: x * 2 — anonymous one-liners
  • map(fn, iterable), filter(fn, iterable)
  • sorted(iterable, key=lambda x: x[1])
  • sum(), len(), any(), all()
  • Combine with comprehensions for readability
nums = [4, 1, 3]
sorted(nums, key=lambda x: -x)
list(map(lambda x: x*x, nums))
list(filter(lambda x: x>1, nums))
any(x > 2 for x in nums)
⚠ Pitfalls:
  • Overusing lambdas hurts readability — prefer named functions for complex logic
  • map()/filter() return iterators in Python 3, wrap in list()
🎯 Use when: Use lambdas for short throwaway functions, especially as a sort/filter key.
⏱ 20-30 min⭐ Intermediate

🟣 Data Structures Deep Dive

📊

List Patterns

Intermediate
  • Comprehensions: [x for x in lst if cond]
  • Nested lists / matrices: grid[i][j]
  • Flatten: [x for row in grid for x in row]
  • Two-pointer & sliding window patterns
  • collections.Counter for frequency counts
matrix = [[1,2],[3,4]]
flat = [x for row in matrix for x in row]
from collections import Counter
Counter("banana")
⚠ Pitfalls:
  • Nested comprehensions can hurt readability — break into loops if unclear
  • Copying nested lists needs copy.deepcopy()
🎯 Use when: Use comprehension patterns for concise data transforms common in interview problems.
⏱ 30-45 min⭐ Intermediate
🔑

Dict & Set Patterns

Intermediate
  • Frequency map: d[x] = d.get(x, 0) + 1
  • collections.defaultdict(int) avoids key errors
  • Membership checks: x in seen_set is O(1)
  • Group items: defaultdict(list)
  • Invert a dict: {v: k for k, v in d.items()}
from collections import defaultdict
count = defaultdict(int)
for ch in "hello":
    count[ch] += 1
seen = set()
seen.add(x)   # O(1) lookup
⚠ Pitfalls:
  • Regular dicts raise KeyError on missing keys — defaultdict avoids that
  • Sets/dicts require hashable keys (no lists)
🎯 Use when: Use dict/set patterns for counting, deduplication, and fast lookups in algorithms.
⏱ 30 min⭐ Intermediate
📦

Stack / Queue / Deque

Intermediate
  • Stack (LIFO): use a list with append()/pop()
  • Queue (FIFO): collections.deque with popleft()
  • deque(maxlen=n) for a fixed-size sliding window
  • queue.Queue for thread-safe queues
  • Deque supports O(1) appends/pops from both ends
from collections import deque
stack = []
stack.append(1); stack.pop()
q = deque()
q.append(1); q.popleft()
⚠ Pitfalls:
  • Using a plain list as a queue (pop(0)) is O(n) — use deque instead
  • Don’t confuse LIFO (stack) with FIFO (queue) order
🎯 Use when: Use deque for BFS, sliding windows, and any queue-like structure needing speed.
⏱ 20-30 min⭐ Intermediate

🟠 Error & File Handling

⚠️

Exceptions

Intermediate
  • try / except / else / finally
  • Catch specific errors: except ValueError as e:
  • Raise manually: raise ValueError("msg")
  • Custom exceptions: class MyErr(Exception): pass
  • finally always runs (cleanup code)
try:
    x = int(input())
except ValueError as e:
    print("Invalid:", e)
else:
    print("OK")
finally:
    print("done")
⚠ Pitfalls:
  • Bare except: catches everything, including KeyboardInterrupt — avoid it
  • Swallowing exceptions silently hides real bugs
🎯 Use when: Wrap risky operations (I/O, parsing, network) in try/except with specific error types.
⏱ 30-40 min⭐ Intermediate
📄

File Handling

Intermediate
  • with open("f.txt") as f: data = f.read()
  • Modes: "r", "w", "a", "rb"
  • Read lines: f.readlines(), iterate for line in f:
  • CSV: csv.reader / csv.DictReader
  • JSON: json.load(), json.dump()
with open("data.txt") as f:
    for line in f:
        print(line.strip())

import json
with open("d.json") as f:
    data = json.load(f)
⚠ Pitfalls:
  • Always use with so files close automatically, even on error
  • "w" mode overwrites the file completely
🎯 Use when: Use the with-statement pattern for any file, network, or resource handling.
⏱ 20-30 min⭐ Intermediate

🟣 Object-Oriented Programming

🏗️

Classes & Objects

Intermediate
  • class Dog: def __init__(self, name): self.name = name
  • Instance vs class variables (per-object vs shared)
  • Methods take self as the first parameter
  • Create object: d = Dog("Rex")
  • Class methods: @classmethod, static: @staticmethod
class Dog:
    species = "Canine"      # class variable
    def __init__(self, name):
        self.name = name      # instance variable
    def bark(self):
        return f"{self.name} says woof"
⚠ Pitfalls:
  • Forgetting self as the first method parameter
  • Class variables are shared — mutating them affects all instances
🎯 Use when: Use classes to bundle related data and behavior together (encapsulation).
⏱ 40-60 min⭐ Intermediate
🧬

Inheritance & Polymorphism

Advanced
  • class Cat(Animal): — base/derived classes
  • super().__init__() calls the parent constructor
  • Method overriding — same method name, different behavior
  • Multiple inheritance: class C(A, B):
  • Duck typing: behavior matters more than exact type
class Animal:
    def speak(self): return "..."
class Cat(Animal):
    def speak(self):
        return "Meow"
class Dog(Animal):
    def speak(self):
        return "Woof"
⚠ Pitfalls:
  • Multiple inheritance can cause MRO (Method Resolution Order) confusion
  • Forgetting super().__init__() skips parent setup logic
🎯 Use when: Use inheritance to share common behavior across related classes.
⏱ 45-60 min⭐ Advanced
🔒

Encapsulation & Abstraction

Advanced
  • Public, _protected, __private (name-mangled) attributes
  • Getters/setters via @property
  • Abstract base classes: abc.ABC, @abstractmethod
  • Hides internal details, exposes a clean interface
  • Encourages modular, maintainable design
from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def area(self): ...

class Circle(Shape):
    def __init__(self, r): self._r = r
    @property
    def area(self): return 3.14 * self._r ** 2
⚠ Pitfalls:
  • __name double underscore triggers name mangling, not true privacy
  • Abstract classes cannot be instantiated directly
🎯 Use when: Use abstraction to define a contract that multiple classes must implement.
⏱ 40-60 min⭐ Advanced

Magic Methods

Advanced
  • __str__ (readable), __repr__ (debug)
  • __len__ lets len(obj) work
  • __iter__ / __next__ make an object iterable
  • __eq__, __lt__ for custom comparisons
  • __enter__/__exit__ for context managers
class Bag:
    def __init__(self): self.items = []
    def __len__(self): return len(self.items)
    def __str__(self): return f"Bag({self.items})"
⚠ Pitfalls:
  • Without __repr__, debugging objects in the console is unreadable
  • __eq__ without __hash__ makes objects unhashable
🎯 Use when: Implement magic methods to make custom objects behave like built-in types.
⏱ 45 min⭐ Advanced

🟣 Modules, Packages & Environment

📦

Modules & Imports

Intermediate
  • import module, from module import name
  • Alias: import numpy as np
  • if __name__ == "__main__": entry point guard
  • Standard library highlights: math, random, datetime, re
  • Relative imports within packages: from . import utils
import math
from datetime import datetime

if __name__ == "__main__":
    print(math.sqrt(16))
⚠ Pitfalls:
  • Circular imports between two modules cause import errors
  • from module import * can silently overwrite names
🎯 Use when: Split large programs into modules for clarity and reuse.
⏱ 20-30 min⭐ Intermediate
📦

Packages & Virtual Environments

Intermediate
  • Create venv: python -m venv venv
  • Activate: venv\Scripts\activate (Win) / source venv/bin/activate
  • Install packages: pip install package
  • Freeze deps: pip freeze > requirements.txt
  • A package is a folder with an __init__.py
python -m venv venv
source venv/bin/activate
pip install requests pandas
pip freeze > requirements.txt
⚠ Pitfalls:
  • Installing packages globally instead of in a venv causes version conflicts
  • Forgetting to commit requirements.txt breaks reproducibility
🎯 Use when: Always isolate project dependencies in a virtual environment.
⏱ 20-30 min⭐ Intermediate

🟢 Data Science & Analytics Libraries

🔢

NumPy

Intermediate
  • np.array([1,2,3]), np.zeros((2,3)), np.arange(10)
  • Slicing like lists but supports multi-dim: a[1:, :2]
  • Vectorized math — no explicit loops needed
  • Aggregates: np.mean(), np.sum(), np.std()
  • Broadcasting lets different-shaped arrays combine automatically
import numpy as np
a = np.array([1,2,3])
a * 2                # [2,4,6]
np.mean(a)
b = np.array([[1,2],[3,4]])
b[:,0]                # first column
⚠ Pitfalls:
  • NumPy arrays are fixed-type — mixing types upcasts everything
  • Broadcasting mismatches raise ValueError on shape errors
🎯 Use when: Use NumPy for fast numerical computation on arrays and matrices.
⏱ 1-2 hrs practice⭐ Intermediate
📊

Pandas

Intermediate
  • Load data: pd.read_csv("file.csv")
  • Inspect: df.head(), df.info(), df.describe()
  • Select: df.loc[rows, cols], df.iloc[0:5, 1:3]
  • Group & aggregate: df.groupby("col").mean()
  • Combine: df.merge(df2, on="id"), handle NaNs with df.dropna()/fillna()
import pandas as pd
df = pd.read_csv("data.csv")
df.head()
df.loc[df.age > 18, "name"]
df.groupby("city")["sales"].sum()
⚠ Pitfalls:
  • loc is label-based, iloc is position-based — don’t mix them up
  • Chained indexing like df[df.x>1]["y"]=0 can trigger SettingWithCopyWarning
🎯 Use when: Use Pandas for loading, cleaning, filtering, and summarizing tabular data.
⏱ 2-3 hrs practice⭐ Intermediate
📈

Matplotlib & Seaborn

Intermediate
  • plt.plot(x, y), plt.bar(), plt.hist(), plt.scatter()
  • Labels: plt.title(), plt.xlabel(), plt.legend()
  • Save: plt.savefig("chart.png")
  • Seaborn adds style: sns.boxplot(), sns.heatmap()
  • plt.subplots() for multi-panel figures
import matplotlib.pyplot as plt
import seaborn as sns
plt.plot(x, y)
plt.title("Trend")
plt.savefig("chart.png")
sns.heatmap(df.corr())
⚠ Pitfalls:
  • Forgetting plt.show() in scripts (not needed in notebooks)
  • Overlapping plots if plt.figure() isn’t called between charts
🎯 Use when: Use Matplotlib/Seaborn to visualize trends, distributions, and correlations.
⏱ 1-2 hrs practice⭐ Intermediate
🤖

Scikit-learn (Overview)

Advanced
  • Split data: train_test_split(X, y, test_size=0.2)
  • Standard workflow: model.fit(X_train, y_train)
  • Predict: model.predict(X_test)
  • Evaluate: accuracy_score(), mean_squared_error()
  • Common models: LinearRegression, LogisticRegression, RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
X_train, X_test, y_train, y_test = train_test_split(X, y)
model = LinearRegression().fit(X_train, y_train)
model.predict(X_test)
⚠ Pitfalls:
  • Not scaling features before distance-based models (e.g., KNN, SVM)
  • Evaluating on training data instead of a held-out test set
🎯 Use when: Use scikit-learn for classic ML workflows: preprocessing, training, evaluation.
⏱ 2-4 hrs practice⭐ Advanced

🔵 Web Development with Python

🌐

Flask

Intermediate
  • @app.route("/path") defines a URL endpoint
  • request.args, request.json read incoming data
  • render_template("page.html") for Jinja2 views
  • jsonify({...}) returns JSON responses
  • Lightweight — great for small APIs and microservices
from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route("/hello")
def hello():
    name = request.args.get("name", "World")
    return jsonify(message=f"Hello {name}")
⚠ Pitfalls:
  • Running with debug=True in production is a security risk
  • Forgetting to set the HTTP method for POST routes (methods=["POST"])
🎯 Use when: Use Flask for small, flexible APIs or microservices without heavy structure.
⏱ 1-2 hrs practice⭐ Intermediate
🏢

Django (High-Level)

Advanced
  • Project = whole site, App = a feature module
  • Models define the ORM database schema
  • Views handle logic, Templates render HTML
  • Built-in admin panel, auth, and ORM out of the box
  • ORM query: Model.objects.filter(field=value)
# models.py
class Post(models.Model):
    title = models.CharField(max_length=200)
    created = models.DateTimeField(auto_now_add=True)

Post.objects.filter(title__icontains="python")
⚠ Pitfalls:
  • Skipping makemigrations/migrate after model changes
  • Django has a steep learning curve for small/simple projects
🎯 Use when: Use Django for full-featured apps needing admin, auth, and ORM built-in.
⏱ 3-5 hrs practice⭐ Advanced

FastAPI

Advanced
  • Path operations: @app.get("/items/{id}")
  • Pydantic models validate request/response data automatically
  • Type hints drive validation and docs generation
  • Automatic interactive docs at /docs (Swagger UI)
  • Built on Starlette — async-first and very fast
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items")
def create(item: Item):
    return item
⚠ Pitfalls:
  • Mixing sync and async routes incorrectly can block the event loop
  • Pydantic validation errors need proper exception handling for clean responses
🎯 Use when: Use FastAPI for modern, high-performance APIs with automatic docs and validation.
⏱ 2-3 hrs practice⭐ Advanced

🟠 Automation, Scripting & Web Scraping

📁

os & sys

Intermediate
  • os.getcwd(), os.listdir(), os.path.join()
  • Env vars: os.environ.get("KEY")
  • CLI args: sys.argv
  • os.makedirs(path, exist_ok=True)
  • sys.exit() to stop a script with a status code
import os, sys
path = os.path.join("data", "file.csv")
os.makedirs("out", exist_ok=True)
name = sys.argv[1] if len(sys.argv) > 1 else "default"
⚠ Pitfalls:
  • Hardcoding file paths with / or \ breaks cross-platform — use os.path.join
  • sys.argv[0] is the script name, not the first real argument
🎯 Use when: Use os/sys for file paths, environment variables, and command-line scripts.
⏱ 20-30 min⭐ Intermediate
⚙️

subprocess

Intermediate
  • subprocess.run(["ls", "-l"]) runs a shell command
  • capture_output=True, text=True to grab output
  • result.returncode checks success (0 = OK)
  • check=True raises an error on failure
  • Avoid shell=True with untrusted input (injection risk)
import subprocess
result = subprocess.run(["echo", "hi"], capture_output=True, text=True)
print(result.stdout)
print(result.returncode)
⚠ Pitfalls:
  • shell=True with user input opens command-injection vulnerabilities
  • Not capturing output leaves stdout/stderr going to the console only
🎯 Use when: Use subprocess to call external programs or shell commands from Python.
⏱ 20-30 min⭐ Intermediate
🌐

Requests

Intermediate
  • requests.get(url, params={...})
  • requests.post(url, json={...})
  • Headers: requests.get(url, headers={...})
  • Parse JSON: response.json()
  • Check status: response.status_code, raise_for_status()
import requests
r = requests.get("https://api.example.com/data", params={"q": "python"})
r.raise_for_status()
data = r.json()
⚠ Pitfalls:
  • Not checking response.status_code before using the response
  • Forgetting timeouts — always pass timeout=5 to avoid hanging requests
🎯 Use when: Use requests to call REST APIs or download web content programmatically.
⏱ 30-45 min⭐ Intermediate
🅿️

BeautifulSoup & Basic Scraping

Intermediate
  • soup = BeautifulSoup(html, "html.parser")
  • Find elements: soup.find("div", class_="x"), find_all()
  • Extract text: tag.text, links: tag["href"]
  • CSS selectors: soup.select(".item > a")
  • Always pair with requests to fetch the HTML first
from bs4 import BeautifulSoup
import requests
html = requests.get(url).text
soup = BeautifulSoup(html, "html.parser")
titles = [a.text for a in soup.select("h2 a")]
⚠ Pitfalls:
  • Scraping without checking a site’s robots.txt/terms of service
  • Sites with JS-rendered content need Selenium, not just BeautifulSoup
🎯 Use when: Use BeautifulSoup for parsing static HTML pages you are permitted to access.
⏱ 45-60 min⭐ Intermediate
🤖

Selenium / Scrapy (Overview)

Advanced
  • Selenium drives a real browser — handles JavaScript-rendered pages
  • Scrapy is a full scraping framework with built-in crawling & pipelines
  • Use Selenium for clicking, logging in, or dynamic content
  • Use Scrapy for large-scale, multi-page structured crawling
  • Both need respect for site terms and rate limiting
# Selenium (conceptual)
# driver.get(url)
# driver.find_element(By.ID, "search").send_keys("python")

# Scrapy (conceptual)
# class MySpider(scrapy.Spider):
#     name = "posts"
⚠ Pitfalls:
  • Selenium is slower and heavier than requests+BeautifulSoup
  • Running headless browsers at scale needs careful resource management
🎯 Use when: Reach for Selenium/Scrapy only when simple requests+BeautifulSoup isn’t enough.
⏱ 1-2 hrs to grasp concepts⭐ Advanced

🔵 Advanced Python Patterns

🔁

Iterators & Generators

Advanced
  • Iterator protocol: iter(obj), next(obj)
  • Generator function uses yield instead of return
  • Generator expression: (x*x for x in range(10))
  • Generators are lazy — values are computed on demand
  • Great for large/infinite sequences without using much memory
def counter(n):
    i = 0
    while i < n:
        yield i
        i += 1

gen = (x*x for x in range(5))
⚠ Pitfalls:
  • A generator is exhausted after one full iteration — can’t restart it
  • Confusing return with yield inside a generator function
🎯 Use when: Use generators when processing large datasets or streams without loading everything into memory.
⏱ 45-60 min⭐ Advanced
🎨

Decorators

Advanced
  • A decorator wraps a function to add behavior: @my_decorator
  • Common uses: logging, timing, access control, caching
  • functools.wraps preserves the original function’s metadata
  • Decorators with arguments need an extra wrapping layer
  • Built-ins: @staticmethod, @classmethod, @property
import functools, time
def timer(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = fn(*args, **kwargs)
        print(time.time() - start)
        return result
    return wrapper

@timer
def slow(): pass
⚠ Pitfalls:
  • Forgetting functools.wraps loses the original function’s name/docstring
  • Stacking multiple decorators applies them bottom-up
🎯 Use when: Use decorators to add cross-cutting behavior (logging, timing, auth) without changing core logic.
⏱ 1 hr practice⭐ Advanced
🔐

Context Managers

Advanced
  • with open(f) as file: handles setup/teardown automatically
  • Custom class-based: implement __enter__ and __exit__
  • Function-based: @contextlib.contextmanager with yield
  • Guarantees cleanup even if an exception occurs
  • Common uses: files, locks, database connections, timers
from contextlib import contextmanager

@contextmanager
def managed_resource():
    print("acquire")
    yield "resource"
    print("release")

with managed_resource() as r:
    print(r)
⚠ Pitfalls:
  • Forgetting that __exit__ must return True to suppress exceptions
  • Not releasing resources properly without the with-statement pattern
🎯 Use when: Use context managers whenever a resource needs guaranteed cleanup (files, connections, locks).
⏱ 45 min⭐ Advanced
🧠

Concurrency Basics (Overview)

Advanced
  • threading: good for I/O-bound tasks, limited by the GIL for CPU-bound work
  • multiprocessing: true parallelism using separate processes (CPU-bound tasks)
  • asyncio: single-threaded concurrency for many I/O-bound tasks (async def, await)
  • Choose based on the bottleneck: I/O vs CPU
  • Concurrency adds complexity — only use it when performance actually requires it
# conceptual overview
# threading.Thread(target=fn).start()
# multiprocessing.Process(target=fn).start()
# async def main():
#     await asyncio.gather(task1(), task2())
⚠ Pitfalls:
  • The GIL means threads don’t speed up CPU-bound Python code — use multiprocessing instead
  • Mixing blocking calls inside asyncio code freezes the event loop
🎯 Use when: Use asyncio/threading for I/O-bound work (network, files); multiprocessing for CPU-heavy work.
⏱ 1-2 hrs to grasp⭐ Advanced

🔀 Quick Comparisons

List vs Tuple vs Set vs Dict

TypeOrderedMutableDuplicatesTypical Use
ListYesYesYesOrdered collection you’ll change
TupleYesNoYesFixed records, dict keys
SetNoYesNoUniqueness, fast membership
DictYes (3.7+)YesKeys: NoKey-based lookup

== vs is

OperatorComparesExample
==Value equality[1,2] == [1,2] → True
isSame object identity[1,2] is [1,2] → False

.loc vs .iloc (Pandas)

AccessorBasisExample
.locLabel-baseddf.loc[3, "name"]
.ilocPosition-based (integers)df.iloc[0, 1]

Flask vs Django vs FastAPI

FrameworkSizeBest ForKey Feature
FlaskMicroSmall APIs, microservicesFlexible, minimal
DjangoFull-stackLarge apps needing admin/ORM/authBatteries included
FastAPIMicro-modernHigh-performance async APIsAuto docs + validation

❓ Frequently Asked Questions

What should I learn first in Python?

Start with variables, data types, strings, and lists, then move to conditionals, loops, and functions before touching OOP or libraries.

Which libraries are most useful for data science?

NumPy and Pandas for data handling, Matplotlib/Seaborn for visualization, and scikit-learn once you’re ready for modeling.

How should I use this cheat sheet for interviews?

Focus on the Data Structures, OOP, and Advanced Patterns sections, and practice writing the code snippets from memory.

What’s the best way to practice these concepts?

Build small projects that combine several cards at once, such as a script that reads a CSV, cleans it with Pandas, and plots a chart.

📩 Get This Cheat Sheet as PDF + Code Files

Enter your details and we’ll send the full PDF version plus downloadable code snippets.

Similar Posts you may get more info >>