Python Cheat Sheet
Modern Python quick reference: data types, comprehensions, strings, files, and common idioms.
Python emphasizes readable expressions, iterable data, and explicit resource management. The examples use Python 3 syntax and focus on standard-library idioms that transfer well between scripts and applications.
Built-in types
Python’s core containers have different mutability and lookup characteristics. Use a list for ordered mutable data, a tuple for fixed records, a dictionary for keyed values, and a set for unique membership.
| Type | Example | Main property |
|---|---|---|
list | [1, 2, 3] | Ordered and mutable. |
tuple | (1, 2, 3) | Ordered and immutable. |
dict | {"id": 7} | Key/value mapping. |
set | {1, 2, 3} | Unique values; fast membership. |
str | "hello" | Immutable Unicode text. |
int | 42 | Arbitrary-precision integer. |
bool | True | Boolean subtype of int. |
None | None | Absence of a value. |
items = ["a", "b"]
point = (10, 20)
user = {"name": "Ada", "active": True}
roles = {"admin", "editor"}
Strings and f-strings
Strings support slicing and methods without changing the original value. F-strings evaluate expressions inside braces and are the usual choice for readable interpolation.
name = "Ada Lovelace"
parts = name.split()
slug = "-".join(part.lower() for part in parts)
clean = " report.txt ".strip().replace(".txt", ".md")
message = f"{name} -> {slug}"
| Expression | Result |
|---|---|
text[0] | First character. |
text[-1] | Last character. |
text[:3] | First three characters. |
text.split(",") | List split on a delimiter. |
", ".join(items) | Join strings with a separator. |
text.strip() | Remove surrounding whitespace. |
text.removeprefix("#") | Remove one exact prefix. |
text.replace("old", "new") | Replace occurrences. |
price = 19.5
print(f"Total: ${price:.2f}")
Comprehensions and iteration
Comprehensions create collections from iterables with an optional filter. Keep them simple; use a normal loop when it improves clarity or requires multiple statements.
squares = [n * n for n in range(10)]
evens = [n for n in range(20) if n % 2 == 0]
lengths = {word: len(word) for word in ["red", "green", "blue"]}
unique_lengths = {len(word) for word in ["red", "green", "blue"]}
for index, value in enumerate(items, start=1):
print(index, value)
for key, value in user.items():
print(key, value)
Dictionaries and lists
Use .get() for optional dictionary keys and sorted() when you need a new ordered list. Mutating methods such as .append() and .sort() return None.
count = user.get("login_count", 0)
user.setdefault("preferences", {})
items.append("c")
items.sort()
ordered = sorted(items, reverse=True)
| Method | Use |
|---|---|
list.append(x) | Add one item at the end. |
list.extend(values) | Add items from an iterable. |
list.pop() | Remove and return an item. |
dict.get(key, default) | Read an optional key. |
dict.items() | Iterate over key/value pairs. |
dict.update(other) | Merge values into a mapping. |
set.add(x) | Add one unique value. |
Control flow and functions
Indentation defines blocks. Functions can have defaults, keyword-only arguments, and type annotations; annotations document intent but are not runtime enforcement by themselves.
def clamp(value: int, low: int = 0, high: int = 100) -> int:
if value < low:
return low
if value > high:
return high
return value
for number in range(5):
if number == 2:
continue
print(clamp(number * 30))
is_even = lambda number: number % 2 == 0
result = list(filter(is_even, range(10)))
Files and context managers
Use with so files close even when reading or writing raises an exception. Specify an encoding for text files when the format requires one.
from pathlib import Path
path = Path("notes.txt")
with path.open("r", encoding="utf-8") as handle:
lines = [line.rstrip("\n") for line in handle]
path.write_text("first line\n", encoding="utf-8")
Virtual environments
A virtual environment isolates project packages from the system interpreter. Create it once, activate it for interactive work, and record dependencies separately from source code.
python3 -m venv .venv
source .venv/bin/activate
python -m pip install requests
python -m pip freeze > requirements.txt
deactivate