lambda / Anonymous Functions
| Since: | Python 2(2000) |
|---|
lambda is a keyword that defines an anonymous function — a function without a name — in a single line. It is commonly used when passing a function object as an argument, such as the key parameter of sorted(), or the first argument of map() and filter(). A lambda body can only contain a single expression, so use a regular def when you need multiple statements.
Syntax
# Basic lambda syntax func = lambda param1, param2: expression # Use with sorted() key sorted(iterable, key=lambda x: x.attribute) # Use with map() and filter() list(map(lambda x: transform_expression, iterable)) list(filter(lambda x: condition_expression, iterable))
Functions & Use Cases
| Function / Use Case | Description |
|---|---|
| lambda param: expression | Defines an anonymous function without a name. |
| sorted(iter, key=lambda) | Specifies the sort key using a lambda. |
| sorted(iter, key=lambda, reverse=True) | Sorts in descending order. |
| map(lambda, iterable) | Returns an iterator that applies the lambda to each element. |
| filter(lambda, iterable) | Returns an iterator of only the elements for which the lambda returns True. |
Sample Code
sample_lambda.py
# lambda: basic anonymous functions
square = lambda x: x ** 2
add = lambda a, b: a + b
print(square(5)) # 25
print(add(3, 4)) # 7
# sorted: specify a sort key with lambda
code_names = ['Hououin', 'Kurisu', 'Mayushii', 'Daru']
sorted_by_length = sorted(code_names, key=lambda s: len(s))
print(sorted_by_length) # ['Daru', 'Kurisu', 'Hououin', 'Mayushii']
# sorted: sort a list of dictionaries
people = [
{'name': 'Okabe Rintaro', 'age': 18, 'song': 'Hacking to the Gate'},
{'name': 'Makise Kurisu', 'age': 18, 'song': 'Gate of Steiner'},
{'name': 'Hashida Itaru', 'age': 19, 'song': 'Believe Me'},
]
sorted_people = sorted(people, key=lambda p: p['age'])
print([p['name'] for p in sorted_people]) # ['Okabe Rintaro', 'Makise Kurisu', 'Hashida Itaru']
# sorted: sort by multiple keys (return a tuple)
data = [('Okabe Rintaro', 18), ('Makise Kurisu', 18), ('Hashida Itaru', 19), ('Shiina Mayuri', 17)]
# Sort by age ascending, then by name ascending
sorted_data = sorted(data, key=lambda x: (x[1], x[0]))
print(sorted_data)
# [('Shiina Mayuri', 17), ('Makise Kurisu', 18), ('Okabe Rintaro', 18), ('Hashida Itaru', 19)]
# map: transform each element
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # [1, 4, 9, 16, 25]
# Note: a list comprehension is often more Pythonic
squares2 = [x ** 2 for x in nums]
# filter: keep only elements that match a condition
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4]
# Combining filter and map
result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, nums)))
print(result) # [4, 16] (squares of even numbers)
# Note: the same result with a list comprehension
result2 = [x ** 2 for x in nums if x % 2 == 0]
Running the code produces the following output:
python3 lambda.py
25
7
['Daru', 'Kurisu', 'Hououin', 'Mayushii']
['Okabe Rintaro', 'Makise Kurisu', 'Hashida Itaru']
[('Shiina Mayuri', 17), ('Makise Kurisu', 18), ('Okabe Rintaro', 18), ('Hashida Itaru', 19)]
[1, 4, 9, 16, 25]
[2, 4]
[4, 16]
Notes
A lambda is essentially the same as defining a regular function with def, but its single-line form makes it convenient to pass inline as an argument. That said, when the logic is complex or you need to debug it, defining a named function with def is usually more readable.
Combining map() and filter() with lambda has long been a common Python pattern, but modern Python considers list comprehensions and generator expressions more readable, and the Python style guide (PEP 8) recommends comprehensions over map()/filter(). Reserve lambda for situations where a comprehension is not a suitable replacement, such as the key parameter of sorted().
If you find any errors or copyright issues, please contact us.