Labs ICT
โญ Pro Login

Lambda

Lambda Functions

A lambda is a small anonymous function defined with lambda instead of def. It can have any number of arguments but only one expression.

Basic Lambda

square = lambda x: x ** 2
print(square(5))

add = lambda a, b: a + b
print(add(3, 7))
Try it Yourself โ†’

Using map()

map() applies a function to every item in an iterable.

nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))
print(squared)
Try it Yourself โ†’

Using filter()

filter() keeps items for which the function returns True.

nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What keyword creates an anonymous function?