A lambda function in Python is a small anonymous function defined using the lambda
keyword. Unlike regular functions defined with the def
keyword, lambda functions are typically used for simple, short operations and are often used in places where functions are required as arguments.
Characteristics of Lambda Functions
- Anonymous: They do not have a name.
- Single expression: They contain only a single expression and return its result.
- Syntax: They are defined using the
lambda
keyword followed by the arguments, a colon, and the expression.
Syntax
lambda arguments: expression
Examples
1. Basic Usage:
A simple lambda function that adds 10 to a given number:
add_ten = lambda x: x + 10 print(add_ten(5)) # Output: 15
2. Multiple Arguments:
A lambda function that multiplies two numbers:
multiply = lambda x, y: x * y print(multiply(3, 4)) # Output: 12
3. Using Lambda with map()
:
Applying a lambda function to each element in a list using map
:
numbers = [1, 2, 3, 4, 5] squared = map(lambda x: x ** 2, numbers) print(list(squared)) # Output: [1, 4, 9, 16, 25]
4. Using Lambda with filter()
:
Filtering a list to get only even numbers using filter
:
numbers = [1, 2, 3, 4, 5, 6] even_numbers = filter(lambda x: x % 2 == 0, numbers) print(list(even_numbers)) # Output: [2, 4, 6]
5. Using Lambda with sorted()
:
Sorting a list of tuples by the second element:
points = [(1, 2), (3, 1), (5, -1), (2, 3)] sorted_points = sorted(points, key=lambda x: x[1]) print(sorted_points) # Output: [(5, -1), (3, 1), (1, 2), (2, 3)]
Here:
- Basic Usage: The lambda function
lambda x: x + 10
takes one argumentx
and returnsx + 10
. - Multiple Arguments: The lambda function
lambda x, y: x * y
takes two argumentsx
andy
and returns their product. - Using Lambda with
map()
: Themap
function applies the lambda functionlambda x: x ** 2
to each element in thenumbers
list, resulting in a list of squared numbers. - Using Lambda with
filter()
: Thefilter
function applies the lambda functionlambda x: x % 2 == 0
to each element in thenumbers
list, returning only the even numbers. - Using Lambda with
sorted()
: Thesorted
function sorts the list of tuplespoints
based on the second element of each tuple, as specified by the lambda functionlambda x: x[1]
.