Python 3 Programming Commands Matrix
The definitive Python 3 developer cheat sheet: list/dict comprehensions, slicing tricks, pathlib file I/O, error handling, virtual environments, and decorators with 1-click copy.
Data Structures & Collections (4 commands)
items = [1, 2, 3]
items.append(4)
items.extend([5, 6])
items.pop()
Mutable list operations: append single element, extend multiple, pop last element.
user = {"id": 1, "role": "admin"}
val = user.get("email", "[email protected]")
Dictionary access using .get() with fallback default if key does not exist.
unique_ids = set([1, 2, 2, 3])
# Result: {1, 2, 3}
Set operations: eliminates duplicates and offers O(1) membership lookup (item in unique_ids).
from collections import defaultdict, Counter
counts = Counter(["apple", "banana", "apple"])
# Result: Counter({'apple': 2, 'banana': 1})
High-performance counting container from the Python standard library.
Slicing & String Operations (3 commands)
seq[start:stop:step]
# items[::-1] reverses entire sequence
Python slice syntax: start (inclusive), stop (exclusive), step stride.
name, score = "Alice", 98.456
msg = f"User {name}: {score:.2f}%"
F-strings with inline formatting: formats numbers to 2 decimal places.
joined = ", ".join(["admin", "editor", "viewer"])
parts = "one,two,three".split(",")
String manipulation: joining iterable with separator and splitting strings.
Comprehensions & Lambdas (4 commands)
squares = [x**2 for x in range(10) if x % 2 == 0]
List comprehension with conditional filter: computes squares of even numbers.
lookup = {user["id"]: user["name"] for user in user_list}
Dictionary comprehension: maps object list into an O(1) ID-to-name lookup index.
sorted_users = sorted(users, key=lambda u: u["age"], reverse=True)
Anonymous lambda function used as custom sort key comparator.
gen = (x * 2 for x in range(1_000_000))
Generator expression using parentheses: evaluates lazily with minimal memory usage.
File I/O & Pathlib (3 commands)
from pathlib import Path
config = Path("config.json")
if config.exists():
data = config.read_text(encoding="utf-8")
Modern, object-oriented Pathlib file operations replacing os.path.
with open("data.csv", "w", encoding="utf-8") as f:
f.write("id,name\n1,Alpha\n")
Context manager ("with" statement) ensuring file descriptor is closed automatically.
import json
with open("data.json", "r") as f:
payload = json.load(f)
print(json.dumps(payload, indent=2))
Parses JSON directly from file stream and serializes to formatted string.
Error Handling & Safety (2 commands)
try:
result = 10 / divisor
except ZeroDivisionError as err:
print(f"Calculation failed: {err}")
finally:
cleanup()
Standard exception handling block with guaranteed finally teardown.
from contextlib import contextmanager
@contextmanager
def timer():
t0 = time.time()
yield
print(f"Elapsed: {time.time() - t0:.4f}s")
Creates a custom context manager using generator and @contextmanager decorator.
Virtual Environments & Pip (3 commands)
python3 -m venv .venv && source .venv/bin/activate
Creates isolated virtual environment and activates it in bash/zsh.
pip install -r requirements.txt
pip freeze > requirements.txt
Installs project dependencies and exports locked versions to file.
python3 -m http.server 8000
Starts instant zero-dependency local HTTP static file server on port 8000.