n Python, the lambda
keyword is used to create anonymous functions, also known as lambda functions. These are small, one-line functions that can take any number of arguments, but can only have one expression. Lambda functions are often used for simple operations that can be defined in a concise manner.
The basic syntax of a lambda function is as follows:
lambda arguments: expression
- The
lambda
keyword is used to define the lambda function. arguments
are the input parameters that the lambda function takes. These are similar to the parameters of a regular named function.expression
is a single expression that the lambda function evaluates and returns as its result.
Lambda Keyword in Python example
Here are a few examples of using the lambda
keyword in Python:
Adds two numbers:
add = lambda x, y: x + y
result = add(5, 3)
print(result) # Output: 8
Checks if a number is even:
is_even = lambda x: x % 2 == 0
print(is_even(6)) # Output: True
print(is_even(7)) # Output: False
Simple Arithmetic Operation:
add = lambda x, y: x + y
result = add(5, 3)
print(result) # Output: 8
Square of a Number:
square = lambda x: x ** 2
result = square(4)
print(result) # Output: 16
Check for Even Numbers:
is_even = lambda x: x % 2 == 0
print(is_even(6)) # Output: True
print(is_even(7)) # Output: False
Sorting a List of Tuples by Second Element:
points = [(2, 5), (1, 8), (3, 2), (4, 7)]
sorted_points = sorted(points, key=lambda point: point[1])
print(sorted_points) # Output: [(3, 2), (2, 5), (4, 7), (1, 8)]
Using Lambda with map
and filter
:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
squared_numbers = list(map(lambda x: x ** 2, numbers))
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(squared_numbers)
print(even_numbers)
Output:
Using Lambda with reduce
from the functools
module:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 120
Lambda functions are typically used when you need a small function for a short period of time, such as when passing a function as an argument to another function, like in the map()
, filter()
, or sorted()
functions:
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
filtered_numbers = list(filter(lambda x: x % 2 == 0, numbers))
While lambda functions can be convenient for simple operations, keep in mind that they have limitations compared to regular named functions. They can’t contain multiple expressions, have complex logic, or include statements other than the expression. In such cases, it’s better to define a regular named function using the def
keyword.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.