Skip to content

Lambda Functions

In Python, a lambda function is an anonymous (unnamed) function defined in a single line using the lambda keyword. They are useful for short operations, such as transforming data or filtering elements, especially when using higher-order functions like map(), filter(), and sorted().

  • Anonymous: They have no defined name.

  • Simple syntax: They are defined with lambda followed by arguments, : and an expression.

  • Single expression: They can only contain a single expression for the result.

  • Use with higher-order functions: They are common with map(), filter() and sorted().

Square of a number.

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

Output:

square.py
25

Function to check if a number is even:

even.py
is_even = lambda x: x % 2 == 0
print(is_even(4))
print(is_even(7))

Output:

even.py
True
False
lambda.py
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)

Output:

lambda.py
[1, 4, 9, 16, 25]
lambda.py
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)

Output:

lambda.py
[2, 4, 6]
lambda.py
words = ['banana', 'pear', 'apple', 'grape']
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)

Output:

lambda.py
['grape', 'pear', 'apple', 'banana']