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
Define a function
def greet(name: str) -> str:
    return f"Hello, {name}"

# Define a function

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

# Default parameter

Keyword-only args
def resize(image, *, width: int, height: int):
    return image, width, height

# Keyword-only args

Arbitrary positional args
def total(*numbers: int) -> int:
    return sum(numbers)

# Arbitrary positional args

Arbitrary keyword args
def render(**context):
    return context

# Arbitrary keyword args

Unpack args into a call
coords = (10, 20)
style = {"color": "red"}
plot(*coords, **style)

# Unpack args into a call

Lambda as key
rows.sort(key=lambda row: row["created_at"])

# Lambda as key

## Comprehensions and generators
List comprehension
squares = [n * n for n in range(10)]

# List comprehension

Filtered list comprehension
evens = [n for n in range(20) if n % 2 == 0]

# Filtered list comprehension

Set comprehension
unique_lengths = {len(word) for word in words}

# Set comprehension

Generator expression
total = sum(n * n for n in range(10))

# Generator expression

Nested comprehension
pairs = [(x, y) for x in xs for y in ys]

# Nested comprehension

Generator function with yield
def countdown(n: int):
    while n > 0:
        yield n
        n -= 1

# Generator function with yield

## Decorators and higher-order functions
Simple decorator
@timer
def build_report():
    return "done"

# Simple decorator

Decorator factory
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

# Decorator factory

Map over data
uppercased = list(map(str.upper, names))

# Map over data

Filter data
valid = list(filter(None, values))

# Filter data

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

# Reduce values

Partial function
from functools import partial
base2 = partial(int, base=2)
value = base2("1010")

# Partial function