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-python3

Virtual 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.txt

Always 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,000

Conditionals

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 iteration

Functions

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

TypeCategoryMutable?ExampleNotes
intNumericNo42, -7, 0xFFArbitrary precision (no overflow)
floatNumericNo3.14, 1e-564-bit double precision
complexNumericNo3+4jRarely used outside math/science
boolNumericNoTrue, FalseSubclass of int (True == 1)
strSequenceNo"hello", 'world'Unicode text, immutable
bytesSequenceNob"hello"Raw byte data
bytearraySequenceYesbytearray(b"hello")Mutable bytes
NoneTypeSingletonNonePython’s null — only one instance

Mutable vs Immutable

Mutable (can change in place)Immutable (creates new object)
list, dict, set, bytearrayint, 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 items

Type Checking

type(42)              # <class 'int'>
isinstance(42, int)   # True (preferred — works with inheritance)
isinstance(42, (int, float))  # True — check multiple types

Collections 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)
MethodDescriptionExample
.append(x)Add to endnums.append(6)
.extend(iterable)Add multiple itemsnums.extend([6, 7])
.insert(i, x)Insert at indexnums.insert(0, 99)
.remove(x)Remove first occurrencenums.remove(3)
.pop(i)Remove and return at indexnums.pop(), nums.pop(0)
.index(x)Find index of valuenums.index(3)
.count(x)Count occurrencesnums.count(3)
.sort()Sort in placenums.sort(), nums.sort(reverse=True)
.reverse()Reverse in placenums.reverse()
.copy()Shallow copynew = 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 4

When 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
MethodDescriptionExample
.keys()All keysuser.keys()
.values()All valuesuser.values()
.items()Key-value pairsfor k, v in user.items():
.get(key, default)Safe accessuser.get("age", 0)
.pop(key)Remove and returnuser.pop("age")
.update(other)Merge another dictuser.update({"age": 31})
.setdefault(key, val)Get or set if missinguser.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 | dict2

Specialized dict types (from collections):

TypePurposeExample
defaultdictAuto-creates missing keys with a default valuedefaultdict(list) — missing keys start as []
OrderedDictPreserves insertion order (mostly redundant since 3.7)When order-comparison matters
CounterCounts occurrencesCounter("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
OperationMethodOperatorResult
Uniona.union(b)a | bAll items from both
Intersectiona.intersection(b)a & bItems in both
Differencea.difference(b)a - bItems in a but not b
Symmetric diffa.symmetric_difference(b)a ^ bItems in one but not both
Subseta.issubset(b)a <= bIs 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

FeatureListTupleDictSet
Ordered?YesYesYes (3.7+)No
Mutable?YesNoYesYes
Duplicates?YesYesKeys: NoNo
Indexed?Yes ([0])Yes ([0])By key (["name"])No
Hashable?NoYesNo (keys must be)No (frozenset is)
Syntax[1, 2, 3](1, 2, 3){"a": 1}{1, 2, 3}
Best forOrdered, changeable dataFixed data, dict keysKey-value lookupUnique items, fast membership

String Operations

Common Methods

MethodDescriptionExample
.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):
    pass

Common Exceptions

ExceptionWhen
ValueErrorRight type, wrong value (int("abc"))
TypeErrorWrong type ("2" + 2)
KeyErrorDict key not found
IndexErrorList index out of range
FileNotFoundErrorFile doesn’t exist
AttributeErrorObject has no such attribute/method
ImportErrorModule not found
ZeroDivisionErrorDivision 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

TermWhat It IsExample
ScriptA single .py file you run directlypython my_script.py
ModuleAny .py file that can be importedimport my_module
PackageA directory of modules with __init__.pyimport mypackage.submodule
LibraryA collection of packages distributed as one unitpip 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_function

Typical 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

ModulePurposeCommon Use
osOS interfaceos.environ, os.getcwd(), os.listdir()
sysSystem/interpretersys.argv, sys.exit(), sys.path
pathlibModern file pathsPath("dir") / "file.txt", .exists(), .read_text()
jsonJSON encode/decodejson.loads(), json.dumps(), json.load()
reRegular expressionsre.search(), re.findall(), re.sub()
subprocessRun shell commandssubprocess.run(["ls", "-la"])
collectionsSpecialized containersdefaultdict, Counter, namedtuple, deque
itertoolsIterator utilitieschain(), product(), groupby(), islice()
functoolsFunction utilitiespartial(), lru_cache, reduce()
dataclassesData-holding classes@dataclass decorator
datetimeDates and timesdatetime.now(), timedelta, .strftime()
loggingLogging frameworklogging.info(), logging.error()
argparseCLI argument parsingBuild command-line interfaces
typingType hintsList[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
deactivate

pyproject.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

ToolWhat It Does
pipStandard package installer
uvFast pip/venv replacement (Rust-based, gaining popularity)
poetryDependency management + packaging
pipxInstall 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+