Cheat SheetsPython A–ZModern Python

Modern Python — Cheat Sheet

Python A–Z · 3 topics. Download the PDF or the Instagram carousel and share it.

Cheat Sheet · AiCanCode.org
Modern Python
Python A–Z3 topicsQuick revision reference
1

Type Hints — Optional, Union, Generics & mypy

Type hints document intent and let tools (mypy, IDEs, FastAPI, Pydantic) catch bugs before runtime — Python stays dynamic, the annotations stay optional but professional.

  • Hints are ignored at runtime — enforced by mypy/pyright, exploited by FastAPI/Pydantic
  • Modern spelling: list[int], dict[str, int], int | None (3.10+)
  • X | None forces callers to handle absence — the end of surprise NoneType errors
  • TypeVar preserves types through functions; Generic parameterizes classes
Signatures, unions, narrowing, aliases
def average(marks: list[int]) -> float:
    return sum(marks) / len(marks)

def find_student(roll: int) -> dict[str, str] | None:   # may be absent
    db = {1: {"name": "Asha"}}
    return db.get(roll)

s = find_student(2)
# print(s["name"])          # mypy error: s might be None!
if s is not None:
    print(s["name"])        # narrowed — mypy happy

# Collections & defaults
def top_k(scores: dict[str, int], k: int = 3) -> list[tuple[str, int]]:
    return sorted(scores.items(), key=lambda kv: -kv[1])[:k]

# Variables & aliases
Matrix = list[list[int]]           # type alias
grid: Matrix = [[1, 2], [3, 4]]

from typing import Callable
def apply_twice(f: Callable[[int], int], x: int) -> int:
    return f(f(x))

# Run the checker:  pip install mypy && mypy app/
2

Modern Idioms — Walrus, Unpacking, Enumerate Patterns & EAFP

The idioms that mark current Python: the walrus operator :=, star-unpacking, dict merging with |, f-string debugging, and choosing EAFP over permission-checking.

  • := assigns within expressions — while (chunk := read()) and match-and-test patterns
  • f"{expr=}" prints both the expression and its value — the fastest debugging
  • dict | dict merges (3.9+); {**a, **b} works everywhere
  • Readable beats clever — use these where they REMOVE noise, not add it
:= assigns inside expressions
# while-read loop — before:
# chunk = f.read(8192)
# while chunk:
#     process(chunk)
#     chunk = f.read(8192)

# after — one place, no repetition:
# while chunk := f.read(8192):
#     process(chunk)

import re
line = "marks: 87"
if m := re.search(r"\d+", line):       # assign + test
    print(int(m.group()))               # 87

# Comprehension: compute once, use twice
def expensive(n):
    return n * n + 1

results = [y for n in range(10) if (y := expensive(n)) > 50]
print(results)                          # [65, 82]

# Don't overuse — if it hurts readability, use two lines.
3

Strings Deep-Dive — Methods, Formatting & Unicode

The string methods that solve interview problems — split/join/strip/find/replace, is* checks, format specs — plus the bytes-vs-str boundary every backend engineer must respect.

  • split() no-arg splits on whitespace runs; sep.join(list) — separator is the caller
  • startswith/endswith accept tuples; removeprefix/removesuffix since 3.9
  • str is Unicode text; bytes is binary — encode()/decode() with explicit utf-8
  • s == s[::-1] for palindromes; casefold() for caseless comparison
The 80% toolbox
s = "  AiCanCode: Campus to Corporate  "

print(s.strip())                    # trim both ends
print(s.lower().count("c"))         # 4
print(s.replace("Corporate", "Job"))

# split/join — the tokenize/detokenize pair
csv_row = "asha,24,pune"
parts = csv_row.split(",")          # ['asha', '24', 'pune']
print("|".join(parts))              # asha|24|pune
words = "to  be   or  not".split() # no arg: any whitespace runs
print(words)                        # ['to','be','or','not']

# Prefix/suffix — tuples allowed!
f = "report.xlsx"
print(f.endswith((".xls", ".xlsx")))   # True
print(f.removesuffix(".xlsx"))         # report (3.9+)

# Char-class checks
print("2026".isdigit(), "abc".isalpha(), "a1".isalnum())

# Case-insensitive compare — use casefold, not lower
print("STRASSE".casefold() == "strasse".casefold())

# Palindrome check, the pythonic way
t = "Malayalam".lower()
print(t == t[::-1])                 # True
Learn this free with Aria, your AI tutor → AiCanCode.org/learn/python