🐍 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.
⚡ 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
Beginnerx = 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
- Python is dynamically typed — variables can change type
bool(0),bool(""),bool([])are all False
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
==compares values,iscompares identity (object reference)- Chained comparisons work:
1 < x < 10
is only for None/singletons; use == for value comparison.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']- Strings are immutable — every “modification” creates a new string
- Use f-strings (3.6+) over
%or.format()for readability
.split()/.join() for parsing and building text.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)
- Mutable — passing a list to a function can change it in place
lst = lst2copies the reference, not the data (use.copy())
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- Forgetting the trailing comma for a 1-item tuple:
(5)is just an int - Cannot append/remove items — tuples are immutable
Sets
Beginner- Create:
s = {1, 2, 3}orset() - 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}{}creates an empty dict, not an empty set — useset()- Sets are unordered — no indexing allowed
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}d["missing"]raisesKeyError— use.get()instead- Dicts keep insertion order since Python 3.7
🎲 Control Flow & Functions
Conditionals
Beginnerif/elif/elsechains- 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"- Do not confuse
=(assignment) with==(comparison) - Watch indentation — Python uses whitespace, not braces
Loops
Beginnerfor item in iterable:,while condition:range(start, stop, step)enumerate(lst)for index+valuezip(a, b)to loop in parallelbreak,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- Infinite loops if the while condition never becomes False
- Modifying a list while iterating over it can skip elements
for for known sequences/iterables, while for condition-based repetition.Functions
Beginnerdef name(params): return value- Default args:
def f(x, y=10): - Variadic:
*args,**kwargs - Scope: local vs global (
globalkeyword) - Type hints:
def f(x: int) -> int:
def greet(name="World", *args, **kwargs):
return f"Hello, {name}!"
def total(*nums):
return sum(nums)- Never use a mutable default argument like
def f(x=[]) - Variables assigned inside a function are local unless declared
global
Lambda & Built-ins
Intermediatelambda x: x * 2— anonymous one-linersmap(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)
- Overusing lambdas hurts readability — prefer named functions for complex logic
map()/filter()return iterators in Python 3, wrap inlist()
🟣 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.Counterfor frequency counts
matrix = [[1,2],[3,4]]
flat = [x for row in matrix for x in row]
from collections import Counter
Counter("banana")- Nested comprehensions can hurt readability — break into loops if unclear
- Copying nested lists needs
copy.deepcopy()
Dict & Set Patterns
Intermediate- Frequency map:
d[x] = d.get(x, 0) + 1 collections.defaultdict(int)avoids key errors- Membership checks:
x in seen_setis 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- Regular dicts raise
KeyErroron missing keys —defaultdictavoids that - Sets/dicts require hashable keys (no lists)
Stack / Queue / Deque
Intermediate- Stack (LIFO): use a
listwithappend()/pop() - Queue (FIFO):
collections.dequewithpopleft() deque(maxlen=n)for a fixed-size sliding windowqueue.Queuefor 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()
- Using a plain list as a queue (
pop(0)) is O(n) — usedequeinstead - Don’t confuse LIFO (stack) with FIFO (queue) order
🟠 Error & File Handling
Exceptions
Intermediatetry / except / else / finally- Catch specific errors:
except ValueError as e: - Raise manually:
raise ValueError("msg") - Custom exceptions:
class MyErr(Exception): pass finallyalways runs (cleanup code)
try:
x = int(input())
except ValueError as e:
print("Invalid:", e)
else:
print("OK")
finally:
print("done")- Bare
except:catches everything, includingKeyboardInterrupt— avoid it - Swallowing exceptions silently hides real bugs
File Handling
Intermediatewith open("f.txt") as f: data = f.read()- Modes:
"r","w","a","rb" - Read lines:
f.readlines(), iteratefor 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)- Always use
withso files close automatically, even on error "w"mode overwrites the file completely
🟣 Object-Oriented Programming
Classes & Objects
Intermediateclass Dog: def __init__(self, name): self.name = name- Instance vs class variables (per-object vs shared)
- Methods take
selfas 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"- Forgetting
selfas the first method parameter - Class variables are shared — mutating them affects all instances
Inheritance & Polymorphism
Advancedclass Cat(Animal):— base/derived classessuper().__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"- Multiple inheritance can cause MRO (Method Resolution Order) confusion
- Forgetting
super().__init__()skips parent setup logic
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__namedouble underscore triggers name mangling, not true privacy- Abstract classes cannot be instantiated directly
Magic Methods
Advanced__str__(readable),__repr__(debug)__len__letslen(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})"- Without
__repr__, debugging objects in the console is unreadable __eq__without__hash__makes objects unhashable
🟣 Modules, Packages & Environment
Modules & Imports
Intermediateimport 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))- Circular imports between two modules cause import errors
from module import *can silently overwrite names
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
- Installing packages globally instead of in a venv causes version conflicts
- Forgetting to commit
requirements.txtbreaks reproducibility
🟢 Data Science & Analytics Libraries
NumPy
Intermediatenp.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
- NumPy arrays are fixed-type — mixing types upcasts everything
- Broadcasting mismatches raise
ValueErroron shape errors
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 withdf.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()locis label-based,ilocis position-based — don’t mix them up- Chained indexing like
df[df.x>1]["y"]=0can trigger SettingWithCopyWarning
Matplotlib & Seaborn
Intermediateplt.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())- Forgetting
plt.show()in scripts (not needed in notebooks) - Overlapping plots if
plt.figure()isn’t called between charts
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)
- Not scaling features before distance-based models (e.g., KNN, SVM)
- Evaluating on training data instead of a held-out test set
🔵 Web Development with Python
Flask
Intermediate@app.route("/path")defines a URL endpointrequest.args,request.jsonread incoming datarender_template("page.html")for Jinja2 viewsjsonify({...})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}")- Running with
debug=Truein production is a security risk - Forgetting to set the HTTP method for POST routes (
methods=["POST"])
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")- Skipping
makemigrations/migrateafter model changes - Django has a steep learning curve for small/simple projects
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- Mixing sync and async routes incorrectly can block the event loop
- Pydantic validation errors need proper exception handling for clean responses
🟠 Automation, Scripting & Web Scraping
os & sys
Intermediateos.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"- Hardcoding file paths with
/or\breaks cross-platform — useos.path.join sys.argv[0]is the script name, not the first real argument
subprocess
Intermediatesubprocess.run(["ls", "-l"])runs a shell commandcapture_output=True, text=Trueto grab outputresult.returncodechecks success (0 = OK)check=Trueraises an error on failure- Avoid
shell=Truewith untrusted input (injection risk)
import subprocess result = subprocess.run(["echo", "hi"], capture_output=True, text=True) print(result.stdout) print(result.returncode)
shell=Truewith user input opens command-injection vulnerabilities- Not capturing output leaves stdout/stderr going to the console only
Requests
Intermediaterequests.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()- Not checking
response.status_codebefore using the response - Forgetting timeouts — always pass
timeout=5to avoid hanging requests
BeautifulSoup & Basic Scraping
Intermediatesoup = 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
requeststo 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")]- Scraping without checking a site’s robots.txt/terms of service
- Sites with JS-rendered content need Selenium, not just BeautifulSoup
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"- Selenium is slower and heavier than requests+BeautifulSoup
- Running headless browsers at scale needs careful resource management
🔵 Advanced Python Patterns
Iterators & Generators
Advanced- Iterator protocol:
iter(obj),next(obj) - Generator function uses
yieldinstead ofreturn - 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))- A generator is exhausted after one full iteration — can’t restart it
- Confusing
returnwithyieldinside a generator function
Decorators
Advanced- A decorator wraps a function to add behavior:
@my_decorator - Common uses: logging, timing, access control, caching
functools.wrapspreserves 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- Forgetting
functools.wrapsloses the original function’s name/docstring - Stacking multiple decorators applies them bottom-up
Context Managers
Advancedwith open(f) as file:handles setup/teardown automatically- Custom class-based: implement
__enter__and__exit__ - Function-based:
@contextlib.contextmanagerwithyield - 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)- Forgetting that
__exit__must return True to suppress exceptions - Not releasing resources properly without the with-statement pattern
Concurrency Basics (Overview)
Advancedthreading: good for I/O-bound tasks, limited by the GIL for CPU-bound workmultiprocessing: 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())
- The GIL means threads don’t speed up CPU-bound Python code — use multiprocessing instead
- Mixing blocking calls inside
asynciocode freezes the event loop
🔀 Quick Comparisons
List vs Tuple vs Set vs Dict
| Type | Ordered | Mutable | Duplicates | Typical Use |
|---|---|---|---|---|
| List | Yes | Yes | Yes | Ordered collection you’ll change |
| Tuple | Yes | No | Yes | Fixed records, dict keys |
| Set | No | Yes | No | Uniqueness, fast membership |
| Dict | Yes (3.7+) | Yes | Keys: No | Key-based lookup |
== vs is
| Operator | Compares | Example |
|---|---|---|
== | Value equality | [1,2] == [1,2] → True |
is | Same object identity | [1,2] is [1,2] → False |
.loc vs .iloc (Pandas)
| Accessor | Basis | Example |
|---|---|---|
.loc | Label-based | df.loc[3, "name"] |
.iloc | Position-based (integers) | df.iloc[0, 1] |
Flask vs Django vs FastAPI
| Framework | Size | Best For | Key Feature |
|---|---|---|---|
| Flask | Micro | Small APIs, microservices | Flexible, minimal |
| Django | Full-stack | Large apps needing admin/ORM/auth | Batteries included |
| FastAPI | Micro-modern | High-performance async APIs | Auto 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.