lambdaIntermediate Examples

Creates a small anonymous (unnamed) function in a single expression

Lambda in higher-order functions

Using lambda with map, filter, and reduce.

python
# map: transform each element
temps_c = [0, 20, 37, 100]
temps_f = list(map(lambda c: c * 9/5 + 32, temps_c))
print(f"Fahrenheit: {temps_f}")

# filter: keep matching elements
numbers = range(1, 21)
primes = list(filter(
    lambda n: n > 1 and all(n % i != 0 for i in range(2, int(n**0.5)+1)),
    numbers
))
print(f"Primes: {primes}")

# sorted with complex key
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
by_age = sorted(people, key=lambda p: p[1])
print(f"By age: {by_age}")

lambda shines as a throwaway function passed to higher-order functions. For anything more than one expression, use def instead.

Want to try these examples interactively?

Open Intermediate Playground