⚡ 100% In-Browser & Private: Your data never leaves your computer. Powered by Cloudflare Edge CDN.
ProWebTools PRO
Developer & SEO Utilities
35+ Recipes

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)

Data Structures & Collections
items = [1, 2, 3] items.append(4) items.extend([5, 6]) items.pop()

Mutable list operations: append single element, extend multiple, pop last element.

PRO TIP items.pop(0) removes from front with O(n) cost; use collections.deque for O(1) pops.
Data Structures & Collections
user = {"id": 1, "role": "admin"} val = user.get("email", "[email protected]")

Dictionary access using .get() with fallback default if key does not exist.

PRO TIP Prevents KeyError exceptions when inspecting API JSON payloads.
Data Structures & Collections
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).

PRO TIP Supports mathematical union (|), intersection (&), and difference (-).
Data Structures & Collections
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.

PRO TIP Use counts.most_common(5) to retrieve the top 5 most frequent items instantly.

Slicing & String Operations (3 commands)

Slicing & String Operations
seq[start:stop:step] # items[::-1] reverses entire sequence

Python slice syntax: start (inclusive), stop (exclusive), step stride.

PRO TIP Works seamlessly on lists, tuples, strings, and byte sequences.
Slicing & String Operations
name, score = "Alice", 98.456 msg = f"User {name}: {score:.2f}%"

F-strings with inline formatting: formats numbers to 2 decimal places.

PRO TIP F-strings are evaluated at runtime and are faster than % formatting or str.format().
Slicing & String Operations
joined = ", ".join(["admin", "editor", "viewer"]) parts = "one,two,three".split(",")

String manipulation: joining iterable with separator and splitting strings.

PRO TIP str.strip() removes whitespace; str.split() without arguments splits on any whitespace.

Comprehensions & Lambdas (4 commands)

Comprehensions & Lambdas
squares = [x**2 for x in range(10) if x % 2 == 0]

List comprehension with conditional filter: computes squares of even numbers.

PRO TIP Idiomatic Python replacement for map() and filter() chains.
Comprehensions & Lambdas
lookup = {user["id"]: user["name"] for user in user_list}

Dictionary comprehension: maps object list into an O(1) ID-to-name lookup index.

PRO TIP Can also build sets: unique_domains = {u["domain"] for u in users}.
Comprehensions & Lambdas
sorted_users = sorted(users, key=lambda u: u["age"], reverse=True)

Anonymous lambda function used as custom sort key comparator.

PRO TIP For cleaner code, consider operator.itemgetter("age") for faster execution.
Comprehensions & Lambdas
gen = (x * 2 for x in range(1_000_000))

Generator expression using parentheses: evaluates lazily with minimal memory usage.

PRO TIP Does not allocate 1,000,000 integers in memory at once; yields one item at a time.

File I/O & Pathlib (3 commands)

File I/O & Pathlib
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.

PRO TIP Pathlib handles Windows and POSIX path separators (slash /) automatically.
File I/O & Pathlib
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.

PRO TIP Always explicitly specify encoding="utf-8" to avoid OS-dependent code-page bugs.
File I/O & Pathlib
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.

PRO TIP Use json.loads() for strings, and json.load() for file streams.

Error Handling & Safety (2 commands)

Error Handling & Safety
try: result = 10 / divisor except ZeroDivisionError as err: print(f"Calculation failed: {err}") finally: cleanup()

Standard exception handling block with guaranteed finally teardown.

PRO TIP Never use bare except: - catch specific exceptions to avoid masking KeyboardInterrupt.
Error Handling & Safety
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.

PRO TIP Usage: with timer(): long_running_task().

Virtual Environments & Pip (3 commands)

Virtual Environments & Pip
python3 -m venv .venv && source .venv/bin/activate

Creates isolated virtual environment and activates it in bash/zsh.

PRO TIP On Windows PowerShell, activate using: .\.venv\Scripts\Activate.ps1.
Virtual Environments & Pip
pip install -r requirements.txt pip freeze > requirements.txt

Installs project dependencies and exports locked versions to file.

PRO TIP Use pip install --upgrade pip before installing packages.
Virtual Environments & Pip
python3 -m http.server 8000

Starts instant zero-dependency local HTTP static file server on port 8000.

PRO TIP Built into standard Python 3 runtime; no npm or external dependencies required.