lambda — Intermediate Playground
Creates a small anonymous (unnamed) function in a single expression
Python Playground
# 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}")
Output
Click "Run" to execute your code
lambda shines as a throwaway function passed to higher-order functions. For anything more than one expression, use def instead.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?