Lambda Functions
A lambda is a small, unnamed function defined in a single expression. They exist for situations where writing a full def function would be overkill for something you'll only use once, right where it's defined.
lambda x: x * x means "a function that takes x and returns x * x" — functionally identical to writing def square(x): return x * x, just condensed to one line. Lambdas can only contain a single expression, not multiple statements.
Where lambdas actually get used
You'll see lambdas most often passed directly into functions like map() (transform every item) and filter() (keep only items matching a condition), where defining a separate named function would be unnecessary ceremony for something this small.
numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x * x, numbers)) print(squared) evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens)
[1, 4, 9, 16, 25] [2, 4]
Next: list comprehensions — Python's more idiomatic alternative to map() and filter() for exactly this kind of thing.
Practice exercise
Write a lambda called double that multiplies its argument by 2, then print double(9).