Python Functions Cheat Sheet
Python function fundamentals covering default arguments, *args/**kwargs, lambdas, type hints, scope rules, and higher-order functions.
Defining Functions
Default arguments and variable-length argument lists.
def greet(name, greeting="Hello"): return f"{greeting}, {name}!"def add_all(*args): # args is a tuple return sum(args)def make_profile(**kwargs): # kwargs is a dict return kwargsgreet("Alice") # 'Hello, Alice!'add_all(1, 2, 3) # 6make_profile(name="Bob", age=30) # {'name': 'Bob', 'age': 30}
Lambda Functions
Anonymous single-expression functions.
square = lambda x: x ** 2square(5) # 25data = [(1, 'c'), (2, 'a'), (3, 'b')]sorted(data, key=lambda x: x[1]) # sort by second element
Type Hints
Optional static typing annotations for parameters and return values.
def add(a: int, b: int) -> int: return a + bdef process(items: list[str], count: int = 0) -> None: ...from typing import Optionaldef find(name: str) -> Optional[int]: return None
Scope: global & nonlocal
Modifying variables from an enclosing scope.
def make_counter(): count = 0 def increment(): nonlocal count # refers to enclosing scope's count count += 1 return count return incrementcounter = make_counter()counter() # 1counter() # 2
Built-in Higher-Order Functions
Functions that take or return other functions.
- map(fn, iterable)- applies fn to every item, returns a map object (lazy)
- filter(fn, iterable)- keeps items where fn(item) is truthy
- functools.reduce(fn, iterable)- cumulatively applies fn to reduce to one value
- sorted(iterable, key=fn)- returns a new sorted list using fn as the sort key
- any(iterable)- True if at least one element is truthy
- all(iterable)- True if every element is truthy
- zip(a, b)- pairs up elements from two or more iterables
Positional-Only & Keyword-Only Parameters
Use / and * markers in a signature to force how arguments must be passed.
def move(x, y, /, *, speed=1): # x, y: positional-only (cannot pass as x=..., y=...) # speed: keyword-only (must pass as speed=...) return (x, y, speed)move(1, 2, speed=5) # OKmove(x=1, y=2) # TypeError: x/y are positional-onlymove(1, 2, 5) # TypeError: speed is keyword-only
Closures & the Late-Binding Trap
Loop variables are captured by reference, not by value, inside closures.
# Bug: every lambda captures the same variable 'i'funcs = [lambda: i for i in range(3)][f() for f in funcs] # [2, 2, 2] -- not [0, 1, 2]!# Fix: bind the current value as a default argumentfuncs = [lambda i=i: i for i in range(3)][f() for f in funcs] # [0, 1, 2]
functools: partial, cache, wraps
Standard-library helpers for composing and optimizing functions.
from functools import partial, lru_cache, wraps# partial: pre-fill some argumentsdouble = partial(pow, exp=2) if False else partial(lambda b, e: b ** e, e=2)# lru_cache: memoize expensive pure functions@lru_cache(maxsize=128)def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)# wraps: preserve __name__/__doc__ when writing decoratorsdef logged(fn): @wraps(fn) def inner(*args, **kwargs): print(f"calling {fn.__name__}") return fn(*args, **kwargs) return inner
Generator Functions with yield
Functions that produce a lazy stream of values instead of returning all at once.
def countdown(n): while n > 0: yield n n -= 1gen = countdown(3)next(gen) # 3next(gen) # 2list(countdown(3)) # [3, 2, 1] -- exhausts the generator# yield from delegates to a sub-generatordef chain(*iterables): for it in iterables: yield from it
Advanced Call & Signature Patterns
Less common but powerful ways functions can be defined or invoked.
- f(*iterable, **mapping)- unpacks an iterable into positional args and a dict into keyword args at the call site
- def f(a, b, *args, c, **kwargs)- args before *args must be positional; params after it are forced keyword-only
- inspect.signature(f)- introspects a callable's parameters at runtime, useful for decorators and validators
- f.__defaults__ / f.__kwdefaults__- tuple/dict of a function's default values, mutable at runtime
- functools.singledispatch- turns a function into a generic one dispatched by the type of its first argument
- operator.itemgetter / attrgetter- fast, picklable alternatives to lambda for use as sort/map keys
- return a, b, c- implicitly packs multiple return values into a tuple, commonly unpacked at the call site
Never use a mutable object like a list or dict as a default argument value — defaults are evaluated once when the function is defined, so all calls share the same object. Use `None` as the default and create the mutable object inside the function body instead.