Codzy

Lambda functions

A lambda is a small, nameless function written on a single line: lambda x: x * x takes x and returns x * x. It contains only one expression, with no return.

It's mostly used as an argument to another function: sorted(..., key=lambda ...) to choose the sorting criterion, map() to transform each item and filter() to keep only some of them.

square = lambda x: x * x
print(square(6))

numbers = [5, 2, 8, 1]
print(sorted(numbers, key=lambda n: -n))
print(list(map(lambda n: n * 10, numbers)))
print(list(filter(lambda n: n > 3, numbers)))

Start the lesson