In Python, a lambda function (also called an anonymous function) is a small, anonymous function that can be defined in a single line of code without a name. It is useful when we need a simple function that we don’t want to define explicitly using the def
keyword.
The basic syntax for a lambda function in Python is:
lambda arguments: expression
Here, arguments
refer to the input arguments for the function and expression
is a single expression that gets evaluated and returned as the result of the function. The result of the expression is automatically returned by the lambda function, so there’s no need to use the return
statement.
For example, the following code defines a lambda function that takes two arguments and returns their sum:
f = lambda x, y: x + y
We can then call the function f
like any other function, passing in the required arguments:
result = f(3, 4)
print(result) # Output: 7
Lambda functions can be used in many contexts where a small, one-time-use function is needed, such as in the map()
, filter()
, and reduce()
functions, or as a key function in the sorted()
function.
Let see some more complex examples
- Multiply two numbers:
multiply = lambda x, y: x * y
result = multiply(3, 4)
print(result) # Output: 12
- Get the length of a string:
string_length = lambda s: len(s)
result = string_length("hello world")
print(result) # Output: 11
- Convert a list of integers to their corresponding square values:
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares) # Output: [1, 4, 9, 16, 25]
- Filter out even numbers from a list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]
- Sort a list of strings based on their length:
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
sorted_fruits = sorted(fruits, key=lambda x: len(x))
print(sorted_fruits) # Output: ['date', 'apple', 'banana', 'cherry', 'elderberry']
Note that in each of these examples, we define a lambda function on the fly and use it as needed, without assigning it a name. This is one of the key benefits of lambda functions, as they allow us to write concise and readable code without cluttering the namespace with unnecessary function names.
Here are some complex examples that demonstrate how lambda functions can be used in real-world scenarios:
- Sorting a list of dictionaries based on a specific key
people = [
{'name': 'Alice', 'age': 25, 'occupation': 'Engineer'},
{'name': 'Bob', 'age': 30, 'occupation': 'Manager'},
{'name': 'Charlie', 'age': 22, 'occupation': 'Intern'},
{'name': 'Dave', 'age': 27, 'occupation': 'Designer'},
]
sorted_people = sorted(people, key=lambda x: x['age'])
print(sorted_people)
Output:
[ {'name': 'Charlie', 'age': 22, 'occupation': 'Intern'}, {'name': 'Alice', 'age': 25, 'occupation': 'Engineer'}, {'name': 'Dave', 'age': 27, 'occupation': 'Designer'}, {'name': 'Bob', 'age': 30, 'occupation': 'Manager'}]
- Filtering a list of files based on their extension
files = ['document.txt', 'picture.jpg', 'report.pdf', 'notes.txt', 'data.csv']
text_files = list(filter(lambda x: x.endswith('.txt'), files))
print(text_files)
Output:
['document.txt', 'notes.txt']