Beginner Fundamentals
Lambda functions
A lambda is a small, anonymous function written on one line. Useful when you need a quick, throwaway function.
double = lambda x: x * 2
print(double(5)) # 10
Equivalent to:
def double(x):
return x * 2
Multiple arguments
add = lambda a, b: a + b
print(add(2, 3)) # 5
Where lambda shines
In functions that take another function, like sorted, map, and filter.
# sort by word length
words = ["banana", "fig", "apple"]
print(sorted(words, key=lambda w: len(w)))
# ['fig', 'apple', 'banana']
# double every number
numbers = [1, 2, 3]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6]
# filter evens
evens = list(filter(lambda x: x % 2 == 0, range(10)))
print(evens) # [0, 2, 4, 6, 8]
For bigger logic, prefer def: a lambda only takes a single expression.