Introducing Lambda Functions
In Python, lambda functions, also known as anonymous functions, are a concise way to define small, one-line functions without a formal function definition. They are defined using the lambda
keyword, followed by one or more parameters, a colon, and the expression to be evaluated.
The general syntax for a lambda function is:
lambda arguments: expression
Here's an example of a lambda function that squares a number:
square = lambda x: x**2
print(square(5)) ## Output: 25
In this example, the lambda function lambda x: x**2
is assigned to the variable square
. When square(5)
is called, the lambda function is executed, and the result 25
is printed.
Lambda functions are particularly useful in the following scenarios:
- Passing Functions as Arguments: Lambda functions can be used as arguments to other functions, such as
map()
, filter()
, and reduce()
, making the code more concise and readable.
- Defining Callback Functions: Lambda functions can be used as callback functions, which are functions passed as arguments to other functions and executed at a later time.
- Sorting and Filtering Data: Lambda functions can be used as the key function in
sorted()
and max()
functions to customize the sorting or filtering behavior.
Here's an example of using a lambda function with the map()
function:
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 map()
function applies the lambda function lambda x: x**2
to each element in the numbers
list, and the resulting squared numbers are stored in the squared_numbers
list.
Lambda functions are a concise and powerful tool in Python, allowing you to define small, one-line functions without the need for a formal function definition.