Skip to main content

Menu

LEVEL 0
0/5 XP
HomeAboutTopicsPricingMy VaultStats

Categories

🤖 Artificial Intelligence
☁️ Cloud and Infrastructure
💾 Data and Databases
💼 Professional Skills
🎯 Programming and Development
🔒 Security and Networking
📚 Specialized Topics
HomeAboutTopicsPricingMy VaultStats
LEVEL 0
0/5 XP
GitHub
© 2026 CheatGrid™. All rights reserved.
Privacy PolicyTerms of UseAboutContact

Python Cheat Sheet

Python Cheat Sheet

Tables
Back to Programming Languages
Updated 2026-03-31
Next Topic: Python Libraries Cheat Sheet

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991, emphasizing code readability through significant whitespace and a philosophy of "there should be one obvious way to do it." It's widely used across web development, data science, automation, machine learning, and systems programming, powered by a vast ecosystem of packages and an active global community. The key to mastering Python isn't just knowing syntax—it's understanding when to use list comprehensions over loops, how duck typing works, and why context managers matter for resource safety.

Quick Index266 entries · 22 tables
Mind Map

22 tables, 266 concepts. Select a concept node to jump to its table row.

Preparing mind map...

Table 1: Data Types

TypeExampleDescription
int
x = 42
• Arbitrary-precision integers
• no overflow limit unlike many languages.
float
y = 3.14
• Double-precision floating-point numbers (64-bit IEEE 754)
• beware rounding errors.
complex
z = 1 + 2j
• Numbers with real and imaginary parts
• j suffix denotes imaginary unit.
str
s = "hello"
• Immutable sequence of Unicode characters
• supports f-strings, slicing, and rich methods.
bool
flag = True
Subclass of int with values True (1) or False (0).
list
arr = [1, 2, 3]
• Mutable ordered sequence
• most versatile collection type.
tuple
t = (1, 2, 3)
• Immutable ordered sequence
• hashable when elements are hashable, useful as dict keys.
dict
d = {"key": "val"}
• Mutable mapping of unique keys to values
• insertion-ordered since Python 3.7.
set
s = {1, 2, 3}
• Mutable unordered collection of unique hashable elements
• supports set operations.
frozenset
fs = frozenset([1, 2])
• Immutable version of set
• hashable, can be dict key or set element.
None
x = None
• Singleton representing absence of value
• distinct from empty collections or zero.
bytes
b = b"data"
• Immutable sequence of byte values (0-255)
• for binary data.
bytearray
ba = bytearray(b"x")
• Mutable version of bytes
• in-place modification of binary data.
range
r = range(10)
• Immutable sequence representing an arithmetic progression
• memory-efficient for iteration.

Table 2: Operators

OperatorExampleDescription
Arithmetic
x + y, x - y, x * y
• Addition, subtraction, multiplication
• work on numbers and some sequences.
Division
x / y
• True division
• always returns float even for integer operands.
Floor division
x // y
• Division rounded down to nearest integer
• result type depends on operands.
Modulo
x % y
• Remainder of division
• sign matches divisor unlike some languages.
Exponentiation
x ** y
• Raises x to power y
• supports negative and fractional exponents.
Comparison
x == y, x != y, x < y
• Equality, inequality, less-than
• chainable like x < y < z.
Identity
x is y
• Tests if objects are same instance
• not value equality.
Membership
x in y
• Checks if x exists in container y
• efficient for sets/dicts.
Logical AND
x and y
• Returns first falsy value or last value if all truthy
• short-circuits.
Logical OR
x or y
• Returns first truthy value or last value if all falsy
• short-circuits.
Logical NOT
not x
• Boolean negation
• returns True if x is falsy.
Bitwise AND
x & y
• Bitwise AND of integers
• also set intersection for sets.
Bitwise OR
x | y
• Bitwise OR of integers
• also set union for sets.
Bitwise XOR
x ^ y
• Bitwise exclusive OR
• also symmetric difference for sets.
Bitwise NOT
~x
• One's complement
• inverts all bits.
Left shift
x << n
• Shifts bits left by n positions
• equivalent to multiplying by 2**n.
Right shift
x >> n
• Shifts bits right by n positions
• equivalent to floor dividing by 2**n.
Dict merge operator
d1 | d2
• Merges two dicts into new dict
• |= updates in-place (Python 3.9+).
Walrus operator
(x := 5)
• Assignment expression
• assigns and returns value in single operation (Python 3.8+).

Table 3: String Operations

MethodExampleDescription
f-strings
f"{x} + {y} = {x+y}"
• Formatted string literals
• fastest and most readable formatting method
• nested quotes and multiline expressions since 3.12.
format()
"{} {}".format(a, b)
• String formatting with positional/keyword arguments
• more verbose than f-strings.
split()
s.split(",")
• Splits string into list by delimiter
• default splits on whitespace.
join()
",".join(items)
• Concatenates iterable into single string with separator
• preferred over += in loops.
strip()
s.strip()
• Removes leading and trailing whitespace
• lstrip()/rstrip() for one side.
removeprefix() / removesuffix()
s.removeprefix("pre")
• Removes exact prefix or suffix if present
• returns unchanged string otherwise (Python 3.9+).
replace()
s.replace("old", "new")
• Returns copy with all occurrences replaced
• optional count parameter.
upper() / lower()
s.upper()
• Case conversion
• casefold() for aggressive case-insensitive comparisons.
startswith() / endswith()
s.startswith("pre")
• Checks if string starts/ends with prefix/suffix
• accepts tuple of options.
find() / index()
s.find("sub")
• Searches substring position
• find() returns -1 if not found, index() raises exception.
isdigit() / isalpha()
s.isdigit()
• Character type checks
• many variants like isalnum(), isspace().
t-strings
t"Hello {name}"
• Template strings producing Template object for custom processing
• generalization of f-strings (Python 3.14+).
%-formatting (legacy)
"%s %d" % (s, n)
• C-style formatting
• replaced by f-strings but still commonly seen in older code.

Table 4: Slicing and Indexing

PatternExampleDescription
Positive indexing
s[0], s[2]
• Zero-based indexing from start
• first element is [0].
Negative indexing
s[-1], s[-2]
• Indexes from end
• -1 is last element, -2 second-to-last.
Basic slice
s[1:4]
Elements from index 1 up to (but not including) 4.
Omit start
s[:3]
• From beginning to index 3
• equivalent to s[0:3].
Omit end
s[2:]
• From index 2 to end
• includes last element.
Full copy
s[:]
Creates shallow copy of entire sequence.
Step slicing
s[::2]
• Every 2nd element
• third parameter is step size.
Reverse
s[::-1]
• Reverses sequence
• negative step iterates backward.
Negative step slice
s[4:1:-1]
From index 4 down to (but not including) 1.

Table 5: Control Flow

StatementExampleDescription
if
if x > 0:
print("pos")
• Conditional execution
• tests truthiness of expression.
elif
elif x == 0:
print("zero")
• Chain multiple conditions
• only first true branch executes.
else
else:
print("neg")
Executes when all if/elif conditions are false.
Ternary expression
x if cond else y
• Inline conditional
• returns x if cond is true, else y.
for loop
for i in range(5):
print(i)
• Iterates over any iterable object
• most common loop type.
while loop
while x > 0:
x -= 1
• Repeats while condition is truthy
• check happens before each iteration.
break
break
Exits innermost enclosing loop immediately.
continue
continue
Skips to next iteration of innermost loop.
else on loops
for i in items:
pass
else:
print("done")
• Executes if loop completes without break
• useful for search patterns.
pass
pass
• Null operation
• syntactic placeholder where statement required.
match-case
match x:
case 1:
print("one")
• Structural pattern matching with guards, captures, and destructuring
• switch-like statement (Python 3.10+).

Table 6: Functions

TechniqueExampleDescription
Function definition
def func(a, b):
return a + b
• Creates reusable code block
• return without value returns None.
Default arguments
def f(x, y=10):
• Parameters with default values
• must come after required params.
Keyword arguments
f(x=1, y=2)
• Named parameters
• allows any order and improves clarity.
*args
def f(*args):
• Variable positional arguments
• collected as tuple.
**kwargs
def f(**kwargs):
• Variable keyword arguments
• collected as dict.
Lambda
lambda x: x * 2
• Anonymous function
• single expression only, no statements.
Docstring
"""Description"""
• First string in function
• accessible via __doc__
• used by help().
Type hints
def f(x: int) -> int:
• Optional annotations
• not enforced at runtime but used by type checkers.
Unpacking in calls
f(*args, **kwargs)
Expands sequences and mappings into function arguments.

Table 7: Comprehensions and Generators

TechniqueExampleDescription
List comprehension
[x**2 for x in range(10)]
• Creates list from iterable
• faster and cleaner than for-loop append.
With condition
[x for x in nums if x > 0]
• Filters elements
• condition acts as inline filter.
Nested comprehension
[x+y for x in a for y in b]
• Multiple for clauses
• left-to-right nesting order.
Dict comprehension
{k: v**2 for k, v in d.items()}
• Creates dict from iterable
• key-value pairs with unique keys.
Set comprehension
{x**2 for x in nums}
• Creates set
• automatically deduplicates results.
Generator expression
(x**2 for x in range(10))
• Lazy evaluation
• memory-efficient for large sequences.
Generator function
def gen():
yield x
• Function with yield
• pauses and resumes execution on each call.
yield from
yield from iterable
• Delegates to subiterator
• simplifies nested generators (Python 3.3+).

Table 8: Classes and OOP

ConceptExampleDescription
Class definition
class Dog:
pass
• Creates new type
• naming convention is PascalCase.
init
def __init__(self, name):
• Constructor
• initializes instance when object created.
Instance attributes
self.name = name
• Per-object data
• defined in __init__ or other methods.
Class attributes
class Dog:
species = "Canis"
• Shared across all instances
• defined at class level.
Methods
def bark(self):
• Functions bound to instance
• first param is self by convention.
Inheritance
class Puppy(Dog):
• Derives from parent class
• inherits attributes and methods.
super()
super().__init__(name)
• Calls parent class method
• handles multiple inheritance correctly.
@property
@property
def age(self):
• Getter method
• accessed like attribute but computed dynamically.
@property.setter
@age.setter
def age(self, val):
• Setter method
• allows validation and side effects on assignment.
@classmethod
@classmethod
def factory(cls):
• Method receives class not instance
• for alternative constructors.
@staticmethod
@staticmethod
def util():
• Regular function in class namespace
• no implicit first parameter.
Multiple inheritance
class C(A, B):
• Inherits from multiple classes
• uses MRO (Method Resolution Order).
str / repr
def __repr__(self):
• String representations
• __repr__ for debugging, __str__ for users.
slots
__slots__ = ('x', 'y')
• Declares fixed attributes
• reduces memory and prevents __dict__ creation.
init_subclass
def __init_subclass__(cls):
• Hook called when class is subclassed
• modern alternative to metaclasses (Python 3.6+).

Table 9: Magic Methods (Dunder Methods)

MethodExampleDescription
init
def __init__(self):
• Instance initialization
• called when object is created.
str
def __str__(self):
• Informal string representation
• used by str() and print().
repr
def __repr__(self):
• Official string representation
• should be valid Python when possible.
len
def __len__(self):
• Returns length
• called by len()
• must return non-negative int.
getitem
def __getitem__(self, key):
• Indexing operator []
• enables subscript access.
setitem
def __setitem__(self, k, v):
• Item assignment [k] = v
• makes object mutable container.
iter
def __iter__(self):
• Returns iterator
• enables for-loop support.
next
def __next__(self):
• Gets next value
• raises StopIteration when exhausted.
enter / exit
def __enter__(self):
• Context manager protocol
• enables with statement.
add
def __add__(self, other):
• Addition operator +
• return new object, don't modify self.
eq
def __eq__(self, other):
• Equality operator ==
• default compares identity.
lt / gt
def __lt__(self, other):
• Comparison operators < and >
• enables sorting.
call
def __call__(self):
• Makes instance callable like function
• enables obj() syntax.
contains
def __contains__(self, item):
• Membership test in
• should return boolean.

Table 10: Exception Handling

TechniqueExampleDescription
try-except
try:
risky()
except ValueError:
• Catches exceptions
• specific types should precede general.
Multiple exceptions
except (ValueError, KeyError):
• Catches multiple types
• tuple of exception classes.
except with variable
except ValueError as e:
• Captures exception object
• access message and details.
else clause
else:
print("success")
• Runs if no exception raised
• before finally.
finally
finally:
cleanup()
• Always executes
• even if exception or return
• for resource cleanup.
raise
raise ValueError("msg")
• Throws exception
• can re-raise caught exception with bare raise.
Custom exceptions
class MyError(Exception):
• Define new exception types
• inherit from Exception or subclass.
Exception chaining
raise NewError() from e
• Links exceptions
• preserves original cause for debugging.
ExceptionGroup
raise ExceptionGroup("msg",
[ValueError(), KeyError()])
• Groups multiple exceptions together
• handled with except* syntax (Python 3.11+).
except*
except* ValueError as eg:
• Catches matching exceptions from an ExceptionGroup
• multiple except* clauses can match different types (Python 3.11+).
Bare except (avoid)
except:
• Catches all exceptions
• dangerous—can hide bugs, use sparingly.

Table 11: File Operations

TechniqueExampleDescription
open() for reading
f = open("file.txt", "r")
• Opens text file
• mode "r" is default
• must close manually.
with statement
with open("f.txt") as f:
• Context manager
• auto-closes file even if exception occurs.
read()
content = f.read()
• Reads entire file as string
• memory-intensive for large files.
readline()
line = f.readline()
• Reads single line
• includes newline character.
readlines()
lines = f.readlines()
• Returns list of all lines
• newlines preserved.
Iterate file
for line in f:
• Memory-efficient line iteration
• preferred over readlines() for large files.
write()
f.write("text")
• Writes string to file
• doesn't add newline automatically.
writelines()
f.writelines(lines)
• Writes sequence of strings
• no newlines added.
Mode "w"
open("f.txt", "w")
• Write mode
• truncates existing file or creates new.
Mode "a"
open("f.txt", "a")
• Append mode
• adds to end of existing file.
Mode "b"
open("f.bin", "rb")
• Binary mode
• for non-text files
• returns bytes objects.
pathlib.Path
Path("f.txt").read_text()
• Object-oriented paths
• cleaner API than os.path
• copy() and move() methods added in 3.14.

Table 12: Modules and Imports

TechniqueExampleDescription
import module
import math
• Imports entire module
• access via math.func().
from import
from math import sqrt
• Imports specific names
• directly accessible without prefix.
import as
import numpy as np
• Aliases module
• shorter name for convenience.
**from import ***
from math import *
• Imports all public names
• discouraged—pollutes namespace.
Relative imports
from . import sibling
• Within packages
• dot notation for current/parent package.
init.py
pkg/__init__.py
• Makes directory a package
• can initialize package and control imports.
if name == "main"
if __name__ == "__main__":
• Checks if script is run directly vs imported
• guards executable code.
sys.path
sys.path.append(dir)
• Module search paths
• modify to add custom locations.
importlib
importlib.import_module(name)
• Dynamic imports
• import by string name at runtime.

Table 13: Common Built-in Functions

FunctionExampleDescription
len()
len([1, 2, 3])
• Returns length of sequence or collection
• calls __len__ method.
range()
range(start, stop, step)
• Generates arithmetic sequence
• stop is exclusive.
enumerate()
enumerate(items, start=0)
• Adds counter to iterable
• returns (index, value) pairs.
zip()
zip(list1, list2)
• Pairs elements from iterables
• stops at shortest input
• strict=True raises if lengths differ (3.10+).
map()
map(func, iterable)
• Applies function to each element
• returns lazy iterator.
filter()
filter(predicate, items)
• Filters elements where predicate is truthy
• lazy iterator.
sum()
sum(numbers, start=0)
• Sums numeric iterable
• optional starting value.
sorted()
sorted(items, key=func)
• Returns new sorted list
• doesn't modify original.
min() / max()
min(items, key=func)
• Returns smallest/largest element
• optional key function.
all()
all([True, True, False])
Returns True if all elements truthy or iterable empty.
any()
any([False, False, True])
Returns True if any element truthy.
reversed()
reversed(seq)
• Returns reverse iterator
• doesn't modify original.
isinstance()
isinstance(obj, type)
• Checks object type
• accepts tuple of types.
type()
type(obj)
• Returns object's type
• for checking use isinstance() instead.
input()
input("Enter: ")
• Reads line from stdin
• always returns string.
print()
print(*values, sep=" ")
• Writes to stdout
• customizable separator and ending.

Table 14: Itertools Module

FunctionExampleDescription
count()
count(start=0, step=1)
• Infinite counter
• useful with zip() or takewhile().
cycle()
cycle([1, 2, 3])
• Repeats iterable infinitely
• saves copy of all elements.
repeat()
repeat(10, times=3)
• Repeats object n times
• infinite if times omitted.
chain()
chain(it1, it2)
• Concatenates iterables
• flattens into single iterator.
pairwise()
pairwise([1, 2, 3])
• Returns overlapping pairs of consecutive elements
• yields (1,2), (2,3) (Python 3.10+).
batched()
batched(range(10), 3)
• Splits iterable into fixed-size tuples
• last batch may be shorter (Python 3.12+).
combinations()
combinations(items, r)
• All r-length combinations
• order doesn't matter, no repeats.
permutations()
permutations(items, r)
• All r-length permutations
• order matters.
product()
product(a, b)
• Cartesian product
• equivalent to nested for-loops.
groupby()
groupby(items, key=func)
• Groups consecutive elements by key
• input must be sorted by same key.
islice()
islice(it, start, stop)
• Slices iterator
• doesn't support negative indices.
accumulate()
accumulate(nums, func)
• Running totals or reductions
• default is sum.
takewhile()
takewhile(pred, it)
• Yields elements while predicate true
• stops at first false.
dropwhile()
dropwhile(pred, it)
• Skips elements while predicate true
• yields rest.
zip_longest()
zip_longest(a, b, fill=None)
Like zip() but continues to longest input with fillvalue.

Table 15: Decorators

TechniqueExampleDescription
Function decorator
@decorator
def func():
• Wraps function to modify behavior
• syntax sugar for func = decorator(func).
Simple decorator
def deco(f):
def wrap():
return f()
return wrap
• Returns wrapper function
• replaces original function.
functools.wraps
@wraps(f)
def wrapper():
• Preserves function metadata (__name__, __doc__)
• use in decorator wrappers.
Decorator with args
@deco(arg)
def func():
• Returns decorator
• three-level nesting: deco(arg)(func)().
Class decorator
@deco
class MyClass:
• Modifies or replaces class
• callable returns class.
Method decorator
@staticmethod
def method():
Built-in decorators like @classmethod, @staticmethod, @property.
Stacking decorators
@deco1
@deco2
def f():
• Multiple decorators
• applied bottom-up: deco1(deco2(f)).
lru_cache
@lru_cache(maxsize=128)
• Memoizes function results
• significant speedup for repeated calls.
functools.cache
@cache
• Simpler unbounded memoization
• shorthand for lru_cache(maxsize=None) (Python 3.9+).

Table 16: Context Managers

TechniqueExampleDescription
with statement
with open("f") as f:
• Ensures resource cleanup
• calls __enter__ and __exit__.
Multiple contexts
with open("a") as f1, open("b") as f2:
• Manages multiple resources
• left-to-right acquisition.
contextlib.contextmanager
@contextmanager
def ctx():
• Creates context manager from generator
• yield separates setup/teardown.
Custom enter / exit
def __enter__(self):
return self
• Implement protocol manually
• __exit__ gets exception info.
contextlib.suppress
with suppress(FileNotFoundError):
• Ignores specified exceptions
• cleaner than try-except pass.
contextlib.closing
with closing(obj):
• Calls close() on exit
• for objects without context manager.
ExitStack
with ExitStack() as stack:
Manages variable number of context managers dynamically.

Table 17: Async/Await (Asyncio)

TechniqueExampleDescription
async def
async def fetch():
• Defines coroutine function
• must be awaited or scheduled as task.
await
result = await coro()
• Suspends coroutine
• yields control to event loop until result ready.
asyncio.run()
asyncio.run(main())
• Entry point
• creates event loop and runs coroutine.
asyncio.create_task()
task = create_task(coro())
• Schedules coroutine
• runs concurrently with other tasks.
asyncio.gather()
await gather(coro1(), coro2())
• Runs multiple coroutines concurrently
• waits for all to complete.
asyncio.TaskGroup
async with TaskGroup() as tg:
tg.create_task(coro())
• Structured concurrency
• auto-cancels remaining tasks on failure (Python 3.11+).
asyncio.timeout()
async with asyncio.timeout(5):
• Context manager with deadline
• raises TimeoutError if exceeded (Python 3.11+).
asyncio.wait_for()
await wait_for(coro(), timeout=5)
• Adds timeout to coroutine
• raises TimeoutError if exceeded.
async for
async for item in async_iter:
• Iterates over async iterable
• calls __aiter__ and __anext__.
async with
async with resource:
• Async context manager
• awaits __aenter__ and __aexit__.
asyncio.sleep()
await asyncio.sleep(1)
• Non-blocking sleep
• yields control to other coroutines.

Table 18: Type Hints

TechniqueExampleDescription
Basic types
x: int = 5
• Annotates variable type
• not enforced at runtime.
Function annotations
def f(x: int) -> str:
• Parameter and return types
• used by type checkers like mypy.
List[T]
items: List[int]
• Homogeneous list
• generic type with element type.
Dict[K, V]
d: Dict[str, int]
Dictionary with specific key/value types.
Optional[T]
x: Optional[int] = None
• Shorthand for Union[T, None]
• accepts value or None.
Union[T1, T2]
x: Union[int, str]
• Multiple allowed types
• modern syntax int | str (Python 3.10+).
Tuple[T, ...]
t: Tuple[int, str]
• Fixed-length tuple with specific types
• ... for variable length.
Callable
f: Callable[[int], str]
• Function type
• list of param types, return type.
Any
x: Any
• Disables type checking
• avoid when possible.
TypeVar
T = TypeVar('T')
• Generic type variable
• for parametric polymorphism.
Protocol
class Sized(Protocol):
• Structural subtyping
• duck typing with type hints.
Literal
x: Literal["a", "b"]
• Restricts to specific values
• for constants.
type statement
type Vector = list[float]
• Declares type alias with lazy evaluation
• replaces TypeAlias annotation (Python 3.12+).
Type parameter syntax
def f[T](x: T) -> T:
• Inline generic type variables on functions and classes
• replaces TypeVar boilerplate (Python 3.12+).
TypeIs
def is_str(x) -> TypeIs[str]:
• Narrows type in both if/else branches
• safer than TypeGuard (Python 3.13+).
@override
@override
def method(self):
• Marks method as overriding parent
• type checkers flag mismatches (Python 3.12+).

Table 19: Regular Expressions

FunctionExampleDescription
re.match()
re.match(r"\d+", s)
• Matches at start of string only
• returns match object or None.
re.search()
re.search(r"\d+", s)
• Searches anywhere in string
• returns first match.
re.findall()
re.findall(r"\d+", s)
• Returns list of all matches
• non-overlapping.
re.finditer()
re.finditer(r"\d+", s)
• Returns iterator of match objects
• memory-efficient for large inputs.
re.sub()
re.sub(r"\d+", "X", s)
• Replaces matches
• accepts function as replacement.
re.split()
re.split(r"\s+", s)
• Splits by pattern
• preserves groups in result.
re.compile()
p = re.compile(r"\d+")
• Precompiles pattern
• faster for reuse.
Groups
m.group(1)
• Captures subpatterns
• group(0) is entire match.
Named groups
(?P<name>\d+)
• Named capture
• access via m.group('name').
re.IGNORECASE
re.search(r"a", s, re.I)
• Case-insensitive matching
• multiple flags with re.I | re.M.
Raw strings
r"\d+"
• Prefix with r
• avoids double-escaping backslashes.

Table 20: Dataclasses and Modern Class Features

TechniqueExampleDescription
@dataclass
@dataclass
class Point:
• Auto-generates __init__, __repr__, etc.
• less boilerplate (Python 3.7+).
Field with default
x: int = 0
• Default values
• mutable defaults require field(default_factory=...).
field()
items: list = field(default_factory=list)
• Customizes field behavior
• prevents shared mutable defaults.
frozen=True
@dataclass(frozen=True)
• Makes instances immutable
• enables hashing for use as dict keys.
slots=True
@dataclass(slots=True)
• Generates __slots__ for reduced memory
• prevents dynamic attribute creation (Python 3.10+).
kw_only=True
@dataclass(kw_only=True)
• Forces keyword-only arguments in __init__
• prevents positional mistakes (Python 3.10+).
post_init
def __post_init__(self):
• Runs after __init__
• for computed fields or validation.
InitVar
temp: InitVar[int]
• Init-only variable
• not stored as field, available in __post_init__.
asdict() / astuple()
asdict(obj)
• Converts dataclass to dict/tuple
• shallow copy by default.
attrs
@define
class C:
• Third-party alternative
• more features than dataclasses.
Pydantic
class User(BaseModel):
• Data validation library
• runtime type checking and JSON schema.

Table 21: Virtual Environments and Package Management

CommandExampleDescription
venv creation
python -m venv myenv
• Creates isolated environment
• includes own Python and pip.
Activation (Unix)
source myenv/bin/activate
• Activates environment
• modifies PATH to use venv Python.
Activation (Windows)
myenv\Scripts\activate.bat
• Windows activation
• PowerShell uses activate.ps1.
Deactivation
deactivate
• Returns to system Python
• works on all platforms.
pip install
pip install package
• Installs package
• use -U for upgrade.
uv
uv pip install package
• Ultra-fast Rust-based package manager
• drop-in replacement for pip, venv, and pip-tools.
pip freeze
pip freeze > requirements.txt
• Exports installed packages
• pinned versions for reproducibility.
pip install -r
pip install -r requirements.txt
• Installs from requirements file
• exact versions specified.
pip list
pip list
• Shows installed packages
• --outdated flag checks for updates.
pip show
pip show package
• Package details
• shows dependencies and install location.
pip uninstall
pip uninstall package
• Removes package
• prompts for confirmation.

Table 22: Advanced Patterns and Idioms

PatternExampleDescription
EAFP
try:
d[k]
except KeyError:
• Easier to Ask Forgiveness than Permission
• Pythonic error handling.
LBYL
if k in d:
x = d[k]
• Look Before You Leap
• less Pythonic, can have race conditions.
Chained comparison
1 < x < 10
• Multiple comparisons
• more readable than 1 < x and x < 10.
Unpacking
a, b, *rest = items
• Extended unpacking
• *rest captures remaining (Python 3.0+).
Dict get() with default
d.get(key, default)
• Safe access
• returns default if key missing, doesn't raise.
setdefault()
d.setdefault(k, []).append(x)
• Gets or creates
• single lookup vs get + assignment.
defaultdict
from collections import defaultdict
• Auto-creates missing keys
• cleaner than setdefault for repeated use.
Counter
Counter(items)
• Counts hashable objects
• dict subclass with counting methods.
namedtuple
Point = namedtuple('Point', 'x y')
• Tuple with named fields
• immutable, memory-efficient alternative to class.
StrEnum
class Color(StrEnum):
RED = auto()
• Enum with string values
• members usable directly as strings (Python 3.11+).
ChainMap
ChainMap(dict1, dict2)
• Groups multiple dicts
• searches sequentially without copying.
functools.reduce()
reduce(lambda x,y: x+y, nums)
• Cumulative operation
• apply function cumulatively to sequence.
functools.partial()
partial(func, arg1)
• Partially applies arguments
• creates new callable with fixed params.
functools.singledispatch()
@singledispatch
def process(arg):
• Type-based function overloading
• dispatches on first argument type.
Singleton pattern
class Singleton(type):
• Ensures single instance
• use metaclass or module for implementation.
Back to Programming Languages
Next Topic: Python Libraries Cheat Sheet

References

Official Documentation

  1. Python Official Documentation - https://docs.python.org/3/
  2. Python Language Reference - https://docs.python.org/3/reference/index.html
  3. Python Standard Library - https://docs.python.org/3/library/index.html
  4. Built-in Types - https://docs.python.org/3/library/stdtypes.html
  5. Data Model - https://docs.python.org/3/reference/datamodel.html
  6. Python Tutorial - https://docs.python.org/3/tutorial/index.html
  7. Python Enhancement Proposals (PEPs) - https://peps.python.org/
  8. PEP 8 - Style Guide for Python Code - https://peps.python.org/pep-0008/
  9. PEP 484 - Type Hints - https://peps.python.org/pep-0484/
  10. PEP 572 - Assignment Expressions (Walrus Operator) - https://peps.python.org/pep-0572/
  11. PEP 584 - Add Union Operators To dict - https://peps.python.org/pep-0584/
  12. PEP 616 - String Methods to Remove Prefixes and Suffixes - https://peps.python.org/pep-0616/
  13. PEP 618 - Add Optional Length-Checking To zip - https://peps.python.org/pep-0618/
  14. PEP 634 - Structural Pattern Matching - https://peps.python.org/pep-0634/
  15. PEP 636 - Structural Pattern Matching Tutorial - https://peps.python.org/pep-0636/
  16. PEP 649 - Deferred Evaluation of Annotations - https://peps.python.org/pep-0649/
  17. PEP 654 - Exception Groups and except* - https://peps.python.org/pep-0654/
  18. PEP 680 - tomllib: Support for Parsing TOML - https://peps.python.org/pep-0680/
  19. PEP 695 - Type Parameter Syntax - https://peps.python.org/pep-0695/
  20. PEP 698 - Override Decorator for Static Typing - https://peps.python.org/pep-0698/
  21. PEP 703 - Making the Global Interpreter Lock Optional - https://peps.python.org/pep-0703/
  22. PEP 750 - Template Strings - https://peps.python.org/pep-0750/
  23. PEP 3107 - Function Annotations - https://peps.python.org/pep-3107/
  24. PEP 257 - Docstring Conventions - https://peps.python.org/pep-0257/
  25. PEP 380 - Syntax for Delegating to a Subgenerator - https://peps.python.org/pep-0380/
  26. Python Glossary - https://docs.python.org/3/glossary.html
  27. What's New in Python 3.10 - https://docs.python.org/3/whatsnew/3.10.html
  28. What's New in Python 3.11 - https://docs.python.org/3/whatsnew/3.11.html
  29. What's New in Python 3.12 - https://docs.python.org/3/whatsnew/3.12.html
  30. What's New in Python 3.13 - https://docs.python.org/3/whatsnew/3.13.html
  31. What's New in Python 3.14 - https://docs.python.org/3/whatsnew/3.14.html
  32. operator module - https://docs.python.org/3/library/operator.html
  33. typing module - https://docs.python.org/3/library/typing.html
  34. collections module - https://docs.python.org/3/library/collections.html
  35. itertools module - https://docs.python.org/3/library/itertools.html
  36. functools module - https://docs.python.org/3/library/functools.html
  37. contextlib module - https://docs.python.org/3/library/contextlib.html
  38. pathlib module - https://docs.python.org/3/library/pathlib.html
  39. re module - https://docs.python.org/3/library/re.html
  40. asyncio module - https://docs.python.org/3/library/asyncio.html
  41. asyncio tasks and coroutines - https://docs.python.org/3/library/asyncio-task.html
  42. asyncio synchronization primitives - https://docs.python.org/3/library/asyncio-sync.html
  43. dataclasses module - https://docs.python.org/3/library/dataclasses.html
  44. enum module - https://docs.python.org/3/library/enum.html
  45. tomllib module - https://docs.python.org/3/library/tomllib.html
  46. concurrent.futures module - https://docs.python.org/3/library/concurrent.futures.html
  47. venv module - https://docs.python.org/3/library/venv.html
  48. pip documentation - https://pip.pypa.io/en/stable/

Technical Blogs & Tutorials

  1. Real Python - https://realpython.com/
  2. Real Python - Python Data Types - https://realpython.com/python-data-types/
  3. Real Python - Primer on Python Decorators - https://realpython.com/primer-on-python-decorators/
  4. Real Python - The Walrus Operator - https://realpython.com/python-walrus-operator/
  5. Real Python - Structural Pattern Matching - https://realpython.com/structural-pattern-matching/
  6. Real Python - Python's with Statement - https://realpython.com/python-with-statement/
  7. Real Python - Python Magic Methods - https://realpython.com/python-magic-methods/
  8. Real Python - Python Descriptors - https://realpython.com/python-descriptors/
  9. Real Python - Python Modules and Packages - https://realpython.com/python-modules-packages/
  10. Real Python - Object-Oriented Programming (OOP) - https://realpython.com/learning-paths/object-oriented-programming-oop-python/
  11. Real Python - Python 3.13 Free Threading and JIT - https://realpython.com/python313-free-threading-jit/
  12. Real Python - Python 3.12 Static Typing Improvements - https://realpython.com/python312-typing/
  13. Real Python - Python 3.14 Template Strings (T-Strings) - https://realpython.com/python-t-strings/
  14. Real Python - Python 3.14 Lazy Annotations - https://realpython.com/python-annotations/
  15. Real Python - Python 3.11 Task and Exception Groups - https://realpython.com/python311-exception-groups/
  16. Real Python - Python 3.11 TOML and tomllib - https://realpython.com/python311-tomllib/
  17. Python Morsels - Pathlib Module - https://www.pythonmorsels.com/pathlib-module/
  18. Python Morsels - Every Dunder Method - https://www.pythonmorsels.com/every-dunder-method/
  19. Python Morsels - Context Managers - https://www.pythonmorsels.com/context-managers/
  20. Python Morsels - Python 3.14 Best New Features - https://www.pythonmorsels.com/python314/
  21. GeeksforGeeks - Python Lambda Functions - https://www.geeksforgeeks.org/python/python-lambda-anonymous-functions-filter-map-reduce/
  22. GeeksforGeeks - Loops in Python - https://www.geeksforgeeks.org/python/loops-in-python/
  23. GeeksforGeeks - Dunder Methods - https://www.geeksforgeeks.org/python/dunder-magic-methods-python/
  24. Medium - Python Control Flow 2026 - https://mayursurani.medium.com/python-control-flow-2026-master-if-else-loops-data-validation-for-data-engineering-complete-c86178202f71
  25. Medium - Python Operators Explained - https://medium.com/@ghoshsiddharth25/python-operators-explained-arithmetic-comparison-logical-bitwise-identity-membership-a765d19355cf
  26. Medium - Python File Handling and Context Managers - https://medium.com/@ghoshsiddharth25/python-file-handling-context-managers-working-with-files-cf4c67e153ab
  27. Medium - Python Modules Packages and Imports - https://medium.com/@ghoshsiddharth25/python-modules-packages-imports-how-python-finds-and-build-code-71e7b8057630
  28. Medium - Lambda Functions Complete Guide - https://medium.com/@brentwash35/lambda-functions-in-python-the-complete-guide-with-real-world-examples-1f1bab9f4964
  29. Medium - Slicing in Python Comprehensive Guide - https://medium.com/data-science/slicing-in-python-a-comprehensive-guide-a609c3bb877c
  30. Medium - Advanced Type Annotations in Python - https://medium.com/@ramanbazhanau/advanced-type-annotations-in-python-part-1-3c9a592e394
  31. Medium - Understanding Magic Methods - https://gdevakumar.medium.com/understanding-magic-methods-in-python-9a736e94736f
  32. Medium - Mastering itertools - https://medium.com/@oz3dprinter/mastering-itertools-advanced-patterns-for-high-performance-python-0e92c8043e68
  33. Medium - Demystifying Metaclasses - https://medium.com/@oz3dprinter/demystifying-metaclasses-and-attributes-in-python-power-tools-you-didnt-know-you-needed-3f2401e4d190
  34. Medium - Python Dataclasses vs Pydantic vs attrs - https://medium.com/@asma.shaikh_19478/python-data-classes-dataclass-vs-attrs-vs-pydantic-14f38e5a67fa
  35. Medium - Stop Using os.path - https://medium.com/@rashmi.rout76/stop-using-os-path-pathlib-will-change-your-life-5b0d12a236c8
  36. Medium - I Rewrote My Code Using Pattern Matching - https://medium.com/the-pythonworld/i-rewrote-my-python-code-using-pattern-matching-the-results-were-wild-8eda0b930441
  37. Medium - Advanced Python Functions 2026 - https://medium.com/@seo.digicrome/advanced-python-functions-and-features-in-2026-a-deep-dive-for-learners-5614772e321b
  38. Medium - Modern Way to Merge Dictionaries in Python 3.9 - https://medium.com/@tihomir.manushev/forget-update-the-modern-way-to-merge-dictionaries-in-python-3-9-09c1ac13c4f0
  39. Medium - Why You Should Be Using zip(strict=True) - https://medium.com/@tihomir.manushev/the-silent-data-killer-in-your-loops-why-you-should-be-using-pythons-zip-strict-true-58e648346183
  40. Medium - Python 3.11 StrEnum and IntEnum - https://sandeepnarayankv.medium.com/python-3-11s-game-changing-strenum-and-intenum-say-goodbye-to-value-forever-778bcf5b8034
  41. Medium - Advanced Enum Patterns auto StrEnum Flag IntEnum - https://viju-londhe.medium.com/advanced-enum-patterns-in-python-auto-strenum-flag-and-intenum-explained-057e69abd2a2
  42. Medium - functools.singledispatch Function Overloading - https://elshad-karimov.medium.com/pythons-functools-singledispatch-the-underrated-power-of-function-overloading-7cb09a65abb2
  43. Medium - 9 New Python Features That Changed How I Code in 2026 - https://medium.com/h7w/9-new-python-features-that-completely-changed-how-i-code-in-2026-youre-probably-ignoring-4-06e9228d76f6
  44. Medium - Most Overlooked Feature in Python Dataclasses - https://medium.com/the-pythonworld/the-most-overlooked-feature-in-pythons-dataclasses-09bddd36e552
  45. Towards Data Science - Guide to Python Comprehensions - https://towardsdatascience.com/a-guide-to-python-comprehensions-4d16af68c97e/
  46. Towards Data Science - Type Hints in Python - https://towardsdatascience.com/type-hints-in-python-1c096f44f375/
  47. Towards Data Science - Path Representation in Python - https://towardsdatascience.com/path-representation-python-712d37917f9d/
  48. OneUptime - How to Use Decorators - https://oneuptime.com/blog/post/2026-01-25-how-to-use-decorators-python/view
  49. OneUptime - How to Handle Exceptions - https://oneuptime.com/blog/post/2026-01-24-handle-exceptions-properly-python/view
  50. OneUptime - How to Use asyncio - https://oneuptime.com/blog/post/2026-01-24-asyncio-concurrent-programming-python/view
  51. OneUptime - How to Use Context Managers - https://oneuptime.com/blog/post/2026-01-22-context-managers-with-statement-python/view
  52. OneUptime - How to Use Regular Expressions - https://oneuptime.com/blog/post/2026-01-23-regular-expressions-python/view
  53. OneUptime - How to Use List Comprehensions - https://oneuptime.com/blog/post/2026-01-25-list-comprehensions-python/view
  54. OneUptime - How to Use itertools Module - https://oneuptime.com/blog/post/2026-01-25-how-to-use-itertools-module-in-python/view
  55. OneUptime - How to Use pathlib - https://oneuptime.com/blog/post/2026-01-27-use-pathlib-for-file-paths-python/view
  56. OneUptime - How to Use f-strings - https://oneuptime.com/blog/post/2026-01-25-fstrings-string-formatting-python/view
  57. OneUptime - How to Use typing Module - https://oneuptime.com/blog/post/2026-01-27-use-typing-module-type-annotations-python/view
  58. OneUptime - How to Create Virtual Environments - https://oneuptime.com/blog/post/2026-01-24-create-virtual-environments-python/view
  59. OneUptime - How to Implement Design Patterns - https://oneuptime.com/blog/post/2025-07-02-python-design-patterns/view
  60. OneUptime - How to Create Metaclasses - https://oneuptime.com/blog/post/2026-01-30-python-metaclasses/view
  61. OneUptime - How to Create Thread Pools - https://oneuptime.com/blog/post/2026-01-30-python-concurrent-futures-thread-pools/view
  62. W3Schools - Python Tutorial - https://www.w3schools.com/python/
  63. W3Schools - Python Data Types - https://www.w3schools.com/python/python_datatypes.asp
  64. W3Schools - Python Try Except - https://www.w3schools.com/python/python_try_except.asp
  65. W3Schools - Python RegEx - https://www.w3schools.com/python/python_regex.asp
  66. W3Schools - Python Virtual Environment - https://www.w3schools.com/python/python_virtualenv.asp
  67. DigitalOcean - How To Index and Slice Strings - https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3
  68. Analytics Vidhya - Control Statements in Python - https://www.analyticsvidhya.com/blog/2021/09/loops-and-control-statements-an-in-depth-python-tutorial/
  69. Analytics Vidhya - Lambda Map Filter and Reduce - https://www.analyticsvidhya.com/blog/2021/10/an-explanation-to-pythons-lambda-map-filter-and-reduce/
  70. Dataquest - Python Classes and Objects 2026 - https://www.dataquest.io/blog/using-classes-in-python/
  71. DataCamp - Python Walrus Operator - https://www.datacamp.com/tutorial/python-walrus-operator
  72. DataCamp - Object-Oriented Programming in Python - https://www.datacamp.com/courses/object-oriented-programming-in-python
  73. DataCamp - Python Dictionary Methods - https://www.datacamp.com/tutorial/python-dictionary-methods
  74. Arjan Codes - Structural Pattern Matching - https://arjancodes.com/blog/how-to-use-structural-pattern-matching-in-python/
  75. Arjan Codes - Python Metaclasses - https://arjancodes.com/blog/understanding-python-metaclasses-for-advanced-class-customization/
  76. The New Stack - Python What's Coming in 2026 - https://thenewstack.io/python-whats-coming-in-2026/
  77. The New Stack - Magic Methods - https://thenewstack.io/magic-methods-the-secret-to-elegant-python-code/
  78. The New Stack - Python Dataclasses Complete Guide - https://thenewstack.io/python-dataclasses-a-complete-guide-to-boilerplatefree-objects/
  79. Toptal - Python Design Patterns - https://www.toptal.com/developers/python/python-design-patterns
  80. Built In - What Is the With Statement - https://builtin.com/software-engineering-perspectives/what-is-with-statement-python
  81. Built In - Why Python Pathlib Excels - https://builtin.com/software-engineering-perspectives/python-pathlib
  82. Hackr.io - Python Operators Guide 2026 - https://hackr.io/blog/python-operators
  83. Python Land - List Comprehension Tutorial - https://python.land/deep-dives/list-comprehension
  84. Mimo - Python Iterator - https://mimo.org/glossary/python/iterator
  85. Mimo - Python Match Statement - https://mimo.org/glossary/python/match-statement
  86. Mimo - Python Context Manager - https://mimo.org/glossary/python/context-manager
  87. Mimo - Python Pathlib Module - https://mimo.org/glossary/python/pathlib
  88. Mimo - Python Formatted Strings - https://mimo.org/glossary/python/formatted-strings
  89. mathspp - Assignment Expressions and Walrus Operator - https://mathspp.com/blog/pydonts/assignment-expressions-and-the-walrus-operator
  90. mathspp - Idiomatic Sequence Slicing - https://mathspp.com/blog/pydonts/idiomatic-sequence-slicing
  91. Packaging Python - Installing Using Pip - https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/
  92. Packaging Python - Distribution vs Import Package - https://packaging.python.org/en/latest/discussions/distribution-package-vs-import-package/
  93. MyPy - Type Hints Cheat Sheet - https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html
  94. attrs Documentation - https://www.attrs.org/
  95. Pydantic Documentation - https://docs.pydantic.dev/
  96. uv Documentation - https://docs.astral.sh/uv/
  97. SQLAlchemy - Integration with dataclasses - http://docs.sqlalchemy.org/en/latest/orm/dataclasses.html
  98. Python Wiki - String Formatting - https://wiki.python.org/python/StringFormatting.html
  99. Codecademy - Python Operators - https://www.codecademy.com/resources/docs/python/operators
  100. Codecademy - Python Files Context Managers - https://www.codecademy.com/resources/docs/python/files/context-managers
  101. igmGuru - Python Modules 2026 - https://www.igmguru.com/blog/python-modules
  102. igmGuru - Python Regular Expressions 2026 - https://www.igmguru.com/blog/python-regular-expressions-regex
  103. igmGuru - Python Classes and Objects 2026 - https://www.igmguru.com/blog/python-classes-and-objects
  104. PyTut - Python Data Types - https://www.pytut.com/data-types/
  105. Dev.to - Mastering Python Async Patterns 2026 - https://dev.to/shehzan/mastering-python-async-patterns-a-complete-guide-to-asyncio-in-2026-10o6
  106. Dev.to - Mastering Slicing and Indexing - https://dev.to/aaron_rose_0787cc8b4775a0/mastering-slicing-and-indexing-in-python-access-data-with-precision-4alp
  107. Dev.to - Dead Simple Python List Comprehensions - https://dev.to/codemouse92/dead-simple-python-list-comprehensions-and-generator-expressions-2mb5
  108. Dev.to - Python Learning Using Context Managers - https://dev.to/vivekyadav200988/python-learning-using-context-managers-in-python-3b76
  109. Dev.to - Mastering Python's Iteration Protocol - https://dev.to/somedood/mastering-pythons-iteration-protocol-iterables-iterators-and-generators-f9e
  110. Dev.to - Explaining Python Type Annotations - https://dev.to/leapcell/explaining-python-type-annotations-a-comprehensive-guide-to-the-typing-module-495i
  111. Sentry Blog - Guide to Errors vs Exceptions - https://blog.sentry.io/practical-tips-on-handling-errors-and-exceptions-in-python/
  112. Honeybadger.io - Guide to Exception Handling - https://www.honeybadger.io/blog/a-guide-to-exception-handling-in-python/
  113. Dagster - Using Type Hinting - https://dagster.io/blog/python-type-hinting
  114. Pyrefly - Why Typed Python - https://pyrefly.org/blog/why-typed-python/
  115. UC Irvine - ICS 33 Context Managers - https://ics.uci.edu/~thornton/ics33/Notes/ContextManagers/
  116. UC Berkeley - CS61A Regular Expressions Study Guide - https://cs61a.org/study-guide/regex/
  117. w3resource - Mastering Python map() filter() reduce() - https://www.w3resource.com/python/functional-programming-map-filter-reduce.php
  118. Buddy.Works - Structural Pattern Matching Tutorial - https://buddy.works/tutorials/structural-pattern-matching-In-python
  119. Linuxize - Python Switch Case Statement - https://linuxize.com/post/python-switch/
  120. Systemweakness - Pathlib Modern Secure File Path Handling - https://systemweakness.com/pathlib-in-python-modern-secure-file-path-handling-e7ee2bf6b5cd
  121. Mostly Python - Remember the Walrus Operator - https://www.mostlypython.com/remember-the-walrus-operator/
  122. Data Dependence - Quick Guide to Slicing - https://datadependence.com/2016/05/python-sequence-slicing-guide/
  123. Seokhyeon Byun - Python Indexing and Slicing - https://www.seokhyeonbyun.com/writing/learning/python/indexing-slicing-python/
  124. mkaz.blog - String Formatting Complete Guide - https://mkaz.blog/working-with-python/string-formatting/
  125. Coursera - Python Decorator Functions - https://www.coursera.org/projects/python-decorator-functions
  126. Namastedev - Advanced Python How to Leverage Decorators - https://namastedev.com/blog/advanced-python-how-to-leverage-decorators-for-clean-code-and-reusability/
  127. Tutorialspoint - Advanced Python Decorators - https://www.tutorialspoint.com/advanced-python-decorators-a-powerful-tool-for-code-modularity
  128. JetBrains Blog - Faster Python Concurrency - https://blog.jetbrains.com/pycharm/2025/06/concurrency-in-async-await-and-threading/
  129. Newline - Python Asyncio for LLM Concurrency - https://www.newline.co/@zaoyang/python-asyncio-for-llm-concurrency-best-practices--bc079176
  130. Quansight Labs - Scaling asyncio on Free-Threaded Python - https://labs.quansight.org/blog/scaling-asyncio-on-free-threaded-python
  131. ealizadeh - Python's itertools Hidden Gem - https://ealizadeh.com/blog/itertools/
  132. takovibe - Python's itertools Power Iterator Patterns - https://takovibe.com/blog/python-itertools/
  133. Bitecode - Back to Basics with pip and venv - https://www.bitecode.dev/p/back-to-basics-with-pip-and-venv
  134. DabApps - Introduction to Pip and Virtualenv - https://www.dabapps.com/insights/introduction-to-pip-and-virtualenv-python/
  135. Python Patterns Guide - Singleton - https://python-patterns.guide/gang-of-four/singleton/
  136. Comparative Analysis of Dataclasses attrs Pydantic - https://arjun.name.np/comparative-analysis-of-dataclasses-attrs-and-pydantic
  137. Bhavaniravi - Pydantic Tips Tricks - https://bhavaniravi.com/blog/python/advanced-python/pydantic-tips-tricks/
  138. InfoWorld - Get Started with Free-Threaded Python 3.13 - https://www.infoworld.com/article/3552750/get-started-with-the-free-threaded-build-of-python-3-13.html
  139. Leapcell - Elegant Code with Structural Pattern Matching Beyond Basics - https://leapcell.io/blog/elegant-code-with-python-s-structural-pattern-matching-beyond-basics
  140. Witty Coder - 15 Essential Ways to Write Better Python Code in 2026 - https://wittycoder.in/blog/15-essential-ways-to-write-better-python-code-in-2026
  141. Rednafi - Explicit Method Overriding with typing.override - https://rednafi.com/python/typing-override/
  142. Stanza - Python Exception Groups and except* Real Examples - https://www.stanza.dev/concepts/python-exception-groups
  143. Snarky.ca - Unravelling t-strings - https://snarky.ca/unravelling-t-strings/
  144. uc4n - Python 3.14 Deferred Annotations PEP 649 Deep Dive - https://uc4n.com/blog/python-deferred-annotations-pep-649
  145. Billy Poon - Structured Concurrency in Python with TaskGroup - https://billypoon.com/insights/structured-concurrency-in-python-with-taskgroup-writing-async-code-that-doesn-t-break

GitHub Repositories & Code Examples

  1. Python Design Patterns - https://github.com/saikotek/python-design-patterns
  2. t-strings PEP 750 Examples - https://github.com/t-strings/pep750-examples

Video Resources

  1. YouTube - Python Control Flow 2026 Tutorial - https://www.youtube.com/watch?v=QlL35pmx66o
  2. YouTube - Advanced Python Programming 2026 Masterclass - https://www.youtube.com/watch?v=c6Ichl84acQ
  3. YouTube - Python Asyncio Tutorial 2026 - https://www.youtube.com/watch?v=MFkat-jelj8
  4. YouTube - Python f-Strings Explained 2026 - https://www.youtube.com/watch?v=kCynS7t6JjU
  5. YouTube - Python Dictionary and Set Comprehensions 2026 - https://www.youtube.com/watch?v=UE0QVegRmHk
  6. YouTube - Python Virtual Environments Explained 2026 - https://www.youtube.com/watch?v=y_uR3GqvaoE
  7. YouTube - Python Libraries vs Modules vs Packages 2026 - https://www.youtube.com/watch?v=XSP2GsjNBfM
  8. YouTube - Python Strings Explained 2026 - https://www.youtube.com/watch?v=ohus9lTffT0
  9. YouTube - Python Operators Explained - https://www.youtube.com/watch?v=IxOp8yd7qy0
  10. YouTube - Advanced Python with Map Filter Reduce - https://www.youtube.com/watch?v=DCZmns4x_wQ
  11. YouTube - Python OOP Full Course - https://www.youtube.com/watch?v=iLRZi0Gu8Go
  12. YouTube - Python Match Case Tutorial - https://www.youtube.com/watch?v=gaUjiWyemyA
  13. YouTube - Magic Methods or Dunder Methods in OOP - https://www.youtube.com/watch?v=Uqj0Xir2YEY
  14. YouTube - Python Assignment Expressions - https://www.youtube.com/watch?v=vPT_3iXyISc
  15. YouTube - StrEnum and IntEnum New Enum Types in Python - https://www.youtube.com/watch?v=AMTZG5W3rKQ
  16. YouTube - Python 3.14 The NEW T-strings are Awesome - https://www.youtube.com/watch?v=vymJMn97wks
  17. YouTube - NEW Generic Alias Syntax for Python 3.12 PEP 695 - https://www.youtube.com/watch?v=YaDYUQ5mD5Q
  18. YouTube - Python Tutorial for Beginners 2026 - https://www.youtube.com/watch?v=j_JuhAWlEaI
  19. YouTube - Learn Python in 2026 Full Course - https://www.youtube.com/watch?v=RL-2Oas3gps

Stack Overflow & Community Resources

  1. Stack Overflow - How can I write a try except block - https://stackoverflow.com/questions/4990718/how-can-i-write-a-try-except-block-that-catches-all-exceptions
  2. Stack Overflow - Create a dictionary with comprehension - https://stackoverflow.com/questions/1747817/create-a-dictionary-with-comprehension
  3. Stack Overflow - How to use filter map and reduce in Python 3 - https://stackoverflow.com/questions/13638898/how-to-use-filter-map-and-reduce-in-python-3
  4. Stack Overflow - Python use Type Hints with Annotations - https://stackoverflow.com/questions/71469513/python-use-type-hints-together-with-annotations
  5. Stack Overflow - Can usage of assignment operator be replaced with walrus - https://stackoverflow.com/questions/78357326/can-any-usage-of-the-assignment-operator-technically-be-replaced-with-the-walrus
  6. Stack Overflow - How to use multiple cases in structural pattern matching - https://stackoverflow.com/questions/74123249/how-to-use-multiple-cases-in-structural-pattern-matching-switch-case-in-python
  7. Stack Overflow - pathlib Path vs os.path.join - https://stackoverflow.com/questions/67112343/pathlib-path-vs-os-path-join-in-python
  8. Stack Overflow - Python3 implementing data descriptor in metaclass - https://stackoverflow.com/questions/63393616/python3-implementing-a-data-descriptor-in-metaclass
  9. Stack Overflow - What is the meaning of magic methods - https://stackoverflow.com/questions/58970686/what-is-the-meaning-of-magic-methods-and-why-do-we-use-it
  10. Stack Overflow - Can every async/await expression is asynchronous - https://stackoverflow.com/questions/75994788/can-every-async-await-expression-is-asynchronous-in-python
  11. Stack Overflow - Fastest way to consume an iterator - https://stackoverflow.com/questions/50937966/fastest-most-pythonic-way-to-consume-an-iterator
  12. Stack Overflow - Conditional or optional context managers - https://stackoverflow.com/questions/41251850/conditional-or-optional-context-managers-in-with-statement
  13. Stack Overflow Engineering - What is more Pythonic way to handle try-except - https://softwareengineering.stackexchange.com/questions/448409/what-is-more-pythonic-way-to-handle-try-except-errors
  14. Reddit - Unleashing Power of Lambda Functions - https://www.reddit.com/r/Python/comments/hsqzc7/python_walrus_operator_assignment_expression/
  15. Reddit - Limiting concurrency in asyncio - https://www.reddit.com/r/Python/comments/12ii45y/limiting_concurrency_in_python_asyncio_the_story/
  16. Reddit - Design Patterns You Should Unlearn - https://www.reddit.com/r/Python/comments/1lfcmky/design_patterns_you_should_unlearn_in_pythonpart1/

More in Programming Languages

  • PHP Programming Language Cheat Sheet
  • Python Libraries Cheat Sheet
  • Arrays & Strings Cheat Sheet
  • Java Cheat Sheet
  • Object-Oriented Programming (OOP) Cheat Sheet
  • TOML Configuration Format Cheat Sheet
View all 31 topics in Programming Languages