Python - Quick Reference
development python cheatsheet reference
Environment Setup
Installing Python
# Ubuntu/Debian
sudo apt update && sudo apt install python3 python3-pip python3-venv
# Check version
python3 --version
# Make 'python' point to python3 (if needed)
sudo apt install python-is-python3Virtual Environments
# Create a virtual environment
python -m venv .venv
# Activate it
source .venv/bin/activate # Linux/macOS
.venv\Scripts\activate # Windows
# Deactivate
deactivate
# Install packages
pip install requests flask
# Save dependencies
pip freeze > requirements.txt
# Install from requirements
pip install -r requirements.txtAlways use a virtual environment. It isolates your project’s dependencies from the system Python and other projects.
Syntax Basics
Variables and Assignment
name = "Alice" # String
age = 30 # Integer
price = 19.99 # Float
is_active = True # Boolean
nothing = None # Null equivalent
# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0
# Type hints (optional, but good practice)
name: str = "Alice"
age: int = 30
scores: list[int] = [90, 85, 92]F-Strings (Formatted Strings)
name = "Alice"
age = 30
print(f"Hello, {name}!") # Hello, Alice!
print(f"{name} is {age} years old") # Alice is 30 years old
print(f"Next year: {age + 1}") # Next year: 31
print(f"Price: ${19.99:.2f}") # Price: $19.99
print(f"{'hello':>10}") # Right-align: hello
print(f"{'hello':<10}") # Left-align: hello
print(f"{1000000:,}") # Thousands: 1,000,000Conditionals
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
# Ternary
status = "adult" if age >= 18 else "minor"
# Truthiness — these are all falsy:
# False, None, 0, 0.0, "", [], {}, set()Loops
# For loop
for item in my_list:
print(item)
# For with index
for i, item in enumerate(my_list):
print(f"{i}: {item}")
# Range
for i in range(5): # 0, 1, 2, 3, 4
for i in range(2, 8): # 2, 3, 4, 5, 6, 7
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
# While
while condition:
do_something()
# Loop control
break # Exit loop entirely
continue # Skip to next iterationFunctions
def greet(name: str, greeting: str = "Hello") -> str:
"""Return a greeting string."""
return f"{greeting}, {name}!"
# Call it
greet("Alice") # "Hello, Alice!"
greet("Bob", greeting="Hi") # "Hi, Bob!"
# *args and **kwargs
def flexible(*args, **kwargs):
print(args) # Tuple of positional args
print(kwargs) # Dict of keyword args
flexible(1, 2, 3, name="Alice", age=30)
# (1, 2, 3)
# {'name': 'Alice', 'age': 30}Data Types Deep Dive
Built-in Types
| Type | Category | Mutable? | Example | Notes |
|---|---|---|---|---|
int | Numeric | No | 42, -7, 0xFF | Arbitrary precision (no overflow) |
float | Numeric | No | 3.14, 1e-5 | 64-bit double precision |
complex | Numeric | No | 3+4j | Rarely used outside math/science |
bool | Numeric | No | True, False | Subclass of int (True == 1) |
str | Sequence | No | "hello", 'world' | Unicode text, immutable |
bytes | Sequence | No | b"hello" | Raw byte data |
bytearray | Sequence | Yes | bytearray(b"hello") | Mutable bytes |
NoneType | Singleton | — | None | Python’s null — only one instance |
Mutable vs Immutable
| Mutable (can change in place) | Immutable (creates new object) |
|---|---|
list, dict, set, bytearray | int, float, str, tuple, frozenset, bytes |
# Immutable — reassignment creates a new object
x = "hello"
x = x + " world" # New string object, old one is garbage collected
# Mutable — modifies the existing object
nums = [1, 2, 3]
nums.append(4) # Same list object, now [1, 2, 3, 4]Why it matters:
- Immutable objects are hashable (can be dict keys or set members)
- Mutable default arguments are a classic Python gotcha:
# BAD — default list is shared across all calls
def add_item(item, items=[]):
items.append(item)
return items
# GOOD — use None as default
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return itemsType Checking
type(42) # <class 'int'>
isinstance(42, int) # True (preferred — works with inheritance)
isinstance(42, (int, float)) # True — check multiple typesCollections in Detail
Lists
Ordered, mutable, allows duplicates. The workhorse collection.
# Creation
nums = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True]
empty = []
from_range = list(range(5)) # [0, 1, 2, 3, 4]
# Indexing and slicing
nums[0] # 1 (first)
nums[-1] # 5 (last)
nums[1:3] # [2, 3] (slice — start inclusive, end exclusive)
nums[:3] # [1, 2, 3] (first 3)
nums[2:] # [3, 4, 5] (from index 2 onward)
nums[::2] # [1, 3, 5] (every 2nd)
nums[::-1] # [5, 4, 3, 2, 1] (reversed)| Method | Description | Example |
|---|---|---|
.append(x) | Add to end | nums.append(6) |
.extend(iterable) | Add multiple items | nums.extend([6, 7]) |
.insert(i, x) | Insert at index | nums.insert(0, 99) |
.remove(x) | Remove first occurrence | nums.remove(3) |
.pop(i) | Remove and return at index | nums.pop(), nums.pop(0) |
.index(x) | Find index of value | nums.index(3) |
.count(x) | Count occurrences | nums.count(3) |
.sort() | Sort in place | nums.sort(), nums.sort(reverse=True) |
.reverse() | Reverse in place | nums.reverse() |
.copy() | Shallow copy | new = nums.copy() |
# List comprehension
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, ...]
evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, 6, ...]Tuples
Ordered, immutable, allows duplicates. Use for fixed collections.
# Creation
point = (3, 4)
single = (42,) # Note the comma — (42) is just an int
rgb = (255, 128, 0)
empty = ()
# Unpacking
x, y = point # x=3, y=4
first, *rest = (1, 2, 3, 4) # first=1, rest=[2, 3, 4]
# Named tuples — tuples with field names
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4When to use tuples vs lists:
- Tuples for fixed data (coordinates, RGB, function return values)
- Lists for collections you’ll modify (append, remove, sort)
- Tuples are hashable — can be dict keys or set members
Dictionaries
Key-value pairs. Ordered (insertion order preserved since Python 3.7), mutable, keys must be unique.
# Creation
user = {"name": "Alice", "age": 30, "active": True}
empty = {}
from_pairs = dict([("a", 1), ("b", 2)])
from_kwargs = dict(name="Alice", age=30)
# Access
user["name"] # "Alice" (KeyError if missing)
user.get("name") # "Alice" (None if missing)
user.get("email", "N/A") # "N/A" (custom default)
# Modify
user["email"] = "alice@example.com" # Add or update
del user["active"] # Remove key| Method | Description | Example |
|---|---|---|
.keys() | All keys | user.keys() |
.values() | All values | user.values() |
.items() | Key-value pairs | for k, v in user.items(): |
.get(key, default) | Safe access | user.get("age", 0) |
.pop(key) | Remove and return | user.pop("age") |
.update(other) | Merge another dict | user.update({"age": 31}) |
.setdefault(key, val) | Get or set if missing | user.setdefault("role", "user") |
# Dict comprehension
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Merge dicts (Python 3.9+)
merged = dict1 | dict2Specialized dict types (from collections):
| Type | Purpose | Example |
|---|---|---|
defaultdict | Auto-creates missing keys with a default value | defaultdict(list) — missing keys start as [] |
OrderedDict | Preserves insertion order (mostly redundant since 3.7) | When order-comparison matters |
Counter | Counts occurrences | Counter("mississippi") → {'s': 4, 'i': 4, ...} |
from collections import defaultdict, Counter
# defaultdict — great for grouping
groups = defaultdict(list)
for name, dept in employees:
groups[dept].append(name)
# Counter
words = ["apple", "banana", "apple", "cherry", "apple"]
counts = Counter(words) # Counter({'apple': 3, 'banana': 1, 'cherry': 1})
counts.most_common(2) # [('apple', 3), ('banana', 1)]Sets
Unordered, mutable, no duplicates. Fast membership testing.
# Creation
colors = {"red", "green", "blue"}
from_list = set([1, 2, 2, 3]) # {1, 2, 3} — duplicates removed
empty = set() # NOT {} — that's an empty dict
# Operations
colors.add("yellow")
colors.remove("red") # KeyError if missing
colors.discard("red") # No error if missing| Operation | Method | Operator | Result |
|---|---|---|---|
| Union | a.union(b) | a | b | All items from both |
| Intersection | a.intersection(b) | a & b | Items in both |
| Difference | a.difference(b) | a - b | Items in a but not b |
| Symmetric diff | a.symmetric_difference(b) | a ^ b | Items in one but not both |
| Subset | a.issubset(b) | a <= b | Is a contained in b? |
# Common use: remove duplicates
unique = list(set(my_list))
# Fast membership testing (O(1) vs O(n) for lists)
valid_codes = {"US", "CA", "UK", "AU"}
if country in valid_codes:
process(country)
# frozenset — immutable set (hashable, can be a dict key)
fs = frozenset([1, 2, 3])Collections Comparison
| Feature | List | Tuple | Dict | Set |
|---|---|---|---|---|
| Ordered? | Yes | Yes | Yes (3.7+) | No |
| Mutable? | Yes | No | Yes | Yes |
| Duplicates? | Yes | Yes | Keys: No | No |
| Indexed? | Yes ([0]) | Yes ([0]) | By key (["name"]) | No |
| Hashable? | No | Yes | No (keys must be) | No (frozenset is) |
| Syntax | [1, 2, 3] | (1, 2, 3) | {"a": 1} | {1, 2, 3} |
| Best for | Ordered, changeable data | Fixed data, dict keys | Key-value lookup | Unique items, fast membership |
String Operations
Common Methods
| Method | Description | Example |
|---|---|---|
.upper() / .lower() | Case conversion | "hello".upper() → "HELLO" |
.strip() | Remove whitespace from ends | " hi ".strip() → "hi" |
.split(sep) | Split into list | "a,b,c".split(",") → ["a","b","c"] |
.join(iterable) | Join list into string | ",".join(["a","b"]) → "a,b" |
.replace(old, new) | Replace substring | "hello".replace("l", "L") |
.startswith(s) | Check prefix | "hello".startswith("he") → True |
.endswith(s) | Check suffix | "file.py".endswith(".py") → True |
.find(s) | Find index (-1 if not found) | "hello".find("ll") → 2 |
.count(s) | Count occurrences | "hello".count("l") → 2 |
.isdigit() | All digits? | "123".isdigit() → True |
.isalpha() | All letters? | "abc".isalpha() → True |
Slicing
s = "Hello, World!"
s[0] # "H"
s[-1] # "!"
s[0:5] # "Hello"
s[7:] # "World!"
s[::-1] # "!dlroW ,olleH" (reversed)File I/O
# Read entire file
with open("data.txt", "r") as f:
content = f.read()
# Read line by line
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
# Write to file
with open("output.txt", "w") as f:
f.write("Hello\n")
# Append to file
with open("output.txt", "a") as f:
f.write("Another line\n")
# JSON
import json
# Read JSON
with open("data.json") as f:
data = json.load(f)
# Write JSON
with open("output.json", "w") as f:
json.dump(data, f, indent=2)
# CSV
import csv
with open("data.csv") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["age"])Always use with statements — they automatically close the file even if an error occurs.
Error Handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Can't divide by zero")
except (ValueError, TypeError) as e:
print(f"Bad value: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No errors occurred")
finally:
print("Always runs")
# Raise your own exceptions
raise ValueError("Invalid input")
# Custom exceptions
class AppError(Exception):
pass
class NotFoundError(AppError):
passCommon Exceptions
| Exception | When |
|---|---|
ValueError | Right type, wrong value (int("abc")) |
TypeError | Wrong type ("2" + 2) |
KeyError | Dict key not found |
IndexError | List index out of range |
FileNotFoundError | File doesn’t exist |
AttributeError | Object has no such attribute/method |
ImportError | Module not found |
ZeroDivisionError | Division by zero |
Common Patterns
# List comprehension with condition
adults = [p for p in people if p.age >= 18]
# Dict comprehension
name_to_age = {p.name: p.age for p in people}
# Unpacking
first, *middle, last = [1, 2, 3, 4, 5] # first=1, middle=[2,3,4], last=5
# Enumerate (index + value)
for i, name in enumerate(names):
print(f"{i}: {name}")
# Zip (iterate parallel lists)
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Lambda (anonymous function)
square = lambda x: x ** 2
sorted_users = sorted(users, key=lambda u: u["age"])
# Map and filter
doubled = list(map(lambda x: x * 2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Walrus operator (:=) — assign in expression
if (n := len(data)) > 10:
print(f"Too much data: {n} items")
# any() / all()
has_errors = any(item.failed for item in results)
all_passed = all(item.passed for item in results)Project Structure
Scripts vs Modules vs Packages vs Libraries
| Term | What It Is | Example |
|---|---|---|
| Script | A single .py file you run directly | python my_script.py |
| Module | Any .py file that can be imported | import my_module |
| Package | A directory of modules with __init__.py | import mypackage.submodule |
| Library | A collection of packages distributed as one unit | pip install requests |
Every script is a module. Every package contains modules.
A library is one or more packages you install via pip.
Script ⊂ Module ⊂ Package ⊂ Library
Import Mechanics
# Import a module
import os
import os.path
# Import specific items
from pathlib import Path
from collections import defaultdict, Counter
# Import with alias
import numpy as np
from datetime import datetime as dt
# Relative imports (within a package)
from . import sibling_module
from ..utils import helper__name__ guard — code that only runs when the file is executed directly (not when imported):
def main():
print("Running as script")
if __name__ == "__main__":
main()__init__.py — marks a directory as a Python package. Can be empty, or can define what gets exported:
# mypackage/__init__.py
from .core import MainClass
from .utils import helper_functionTypical Project Layout
my-project/
├── src/
│ └── mypackage/
│ ├── __init__.py
│ ├── core.py
│ ├── utils.py
│ └── models.py
├── tests/
│ ├── test_core.py
│ └── test_utils.py
├── .venv/
├── .gitignore
├── pyproject.toml # Modern project config (replaces setup.py)
├── requirements.txt # or managed by pyproject.toml
└── README.md
Standard Library Highlights
| Module | Purpose | Common Use |
|---|---|---|
os | OS interface | os.environ, os.getcwd(), os.listdir() |
sys | System/interpreter | sys.argv, sys.exit(), sys.path |
pathlib | Modern file paths | Path("dir") / "file.txt", .exists(), .read_text() |
json | JSON encode/decode | json.loads(), json.dumps(), json.load() |
re | Regular expressions | re.search(), re.findall(), re.sub() |
subprocess | Run shell commands | subprocess.run(["ls", "-la"]) |
collections | Specialized containers | defaultdict, Counter, namedtuple, deque |
itertools | Iterator utilities | chain(), product(), groupby(), islice() |
functools | Function utilities | partial(), lru_cache, reduce() |
dataclasses | Data-holding classes | @dataclass decorator |
datetime | Dates and times | datetime.now(), timedelta, .strftime() |
logging | Logging framework | logging.info(), logging.error() |
argparse | CLI argument parsing | Build command-line interfaces |
typing | Type hints | List[int], Optional[str], Dict[str, Any] |
Virtual Environments & Dependencies
venv Workflow
# Create
python -m venv .venv
# Activate
source .venv/bin/activate
# Install packages
pip install requests flask
# Save exact versions
pip freeze > requirements.txt
# Reproduce elsewhere
pip install -r requirements.txt
# Deactivate
deactivatepyproject.toml (Modern Standard)
[project]
name = "my-project"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = [
"requests>=2.28",
"flask>=3.0",
]
[project.optional-dependencies]
dev = ["pytest", "ruff"]Alternative Tools
| Tool | What It Does |
|---|---|
| pip | Standard package installer |
| uv | Fast pip/venv replacement (Rust-based, gaining popularity) |
| poetry | Dependency management + packaging |
| pipx | Install CLI tools in isolated environments |
Useful One-Liners
# Quick HTTP server (serves current directory)
python -m http.server 8000
# Pretty-print JSON
cat data.json | python -m json.tool
# Run a quick script
python -c "print('Hello')"
# Install and run a package
pipx run cowsay "hello"# Flatten a nested list
flat = [item for sublist in nested for item in sublist]
# Reverse a string
reversed_s = s[::-1]
# Remove duplicates preserving order
unique = list(dict.fromkeys(my_list))
# Merge two dicts
merged = {**dict1, **dict2} # Python 3.5+
merged = dict1 | dict2 # Python 3.9+