Python Functions and Comprehensions

Functions, parameters, lambda, decorators, comprehensions, generators, and functional helpers.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Functions

Function definitions and calling conventions.

Define a function

Define a function

pythonANYfunctionsbasics
python
def greet(name: str) -> str:
    return f"Hello, {name}"

Default parameter

Default parameter

pythonANYfunctionsdefaults
python
def connect(host: str, port: int = 5432) -> tuple[str, int]:
    return host, port

Keyword-only args

Keyword-only args

pythonANYfunctionsparameters
python
def resize(image, *, width: int, height: int):
    return image, width, height

Arbitrary positional args

Arbitrary positional args

pythonANYfunctionsargs
python
def total(*numbers: int) -> int:
    return sum(numbers)

Arbitrary keyword args

Arbitrary keyword args

pythonANYfunctionskwargs
python
def render(**context):
    return context

Unpack args into a call

Unpack args into a call

pythonANYunpackingcalls
python
coords = (10, 20)
style = {"color": "red"}
plot(*coords, **style)

Lambda as key

Lambda as key

pythonANYlambdafunctions
python
rows.sort(key=lambda row: row["created_at"])

Comprehensions and generators

Compact collection-building and lazy iteration.

List comprehension

List comprehension

pythonANYcomprehensionlist
python
squares = [n * n for n in range(10)]

Filtered list comprehension

Filtered list comprehension

pythonANYcomprehensionlist
python
evens = [n for n in range(20) if n % 2 == 0]

Set comprehension

Set comprehension

pythonANYcomprehensionset
python
unique_lengths = {len(word) for word in words}

Generator expression

Generator expression

pythonANYgeneratorexpression
python
total = sum(n * n for n in range(10))

Nested comprehension

Nested comprehension

pythonANYcomprehensionnested
python
pairs = [(x, y) for x in xs for y in ys]

Generator function with yield

Generator function with yield

pythonANYyieldgenerator
python
def countdown(n: int):
    while n > 0:
        yield n
        n -= 1

Decorators and higher-order functions

Reusable wrappers and functional patterns.

Simple decorator

Simple decorator

pythonANYdecoratorfunctions
python
@timer
def build_report():
    return "done"

Decorator factory

Decorator factory

pythonANYdecoratorretry
python
def retry(times: int):
    def decorator(fn):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                try:
                    return fn(*args, **kwargs)
                except Exception:
                    pass
            return fn(*args, **kwargs)
        return wrapper
    return decorator

Map over data

Map over data

pythonANYmapfunctional
python
uppercased = list(map(str.upper, names))

Filter data

Filter data

pythonANYfilterfunctional
python
valid = list(filter(None, values))

Reduce values

Reduce values

pythonANYreducefunctools
python
from functools import reduce
product = reduce(lambda a, b: a * b, numbers, 1)

Partial function

Partial function

pythonANYpartialfunctools
python
from functools import partial
base2 = partial(int, base=2)
value = base2("1010")