Introduction to Python Lambda
Python Lambda
A lambda function, also known as an anonymous function, is a way to create small, one-line functions without explicitly defining them using the def keyword.
Lambda functions are typically used for simple tasks or as arguments to higher-order functions.
The syntax for a lambda function is as follows:
lambda arguments: expression
Here's an example that demonstrates the usage of a lambda function to calculate the square of a number:
square = lambda x: x ** 2
result = square(5)
print(result) # Output: 25
In this example:
- The lambda function takes a single argument
x
and returns the square ofx
using the expressionx ** 2
. - The lambda function is assigned to the variable
square
, and then it is called with the value5
as the argument.
Lambda functions can also take multiple arguments:
add = lambda x, y: x + y
result = add(3, 4)
print(result) # Output: 7
In this example:
- The lambda function takes two arguments
x
andy
and returns their sum using the expressionx + y
.
They are commonly used in combination with higher-order functions like map()
, filter()
, and reduce()
.
You can use a lambda function with map()
to apply a transformation to each element of a list.
As an example:
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
In this example:
- The lambda function is used as the first argument to
map()
. - It takes each element
x
from thenumbers
list and returns its square. - The resulting squared numbers are collected into a new list using
list()
.