Lambda Functions
Write tiny anonymous functions in a single expression.
Syntax
lambda params: expressionA lambda is a small, unnamed function written in one line. It is limited to a single expression, whose value is returned automatically.
Where they shine
Lambdas are handy as short throwaway functions passed to sorted(), map(), or filter() — anywhere a quick function is needed.
Example
square = lambda x: x * x
print(square(5))
people = [('Ada', 36), ('Grace', 45), ('Alan', 41)]
people.sort(key=lambda p: p[1])
print(people)
# Output:
# 25
# [('Ada', 36), ('Alan', 41), ('Grace', 45)]When to use it
- A sort call uses a lambda as the 'key' to sort a list of dicts by a specific field.
- A map() call applies a lambda to convert every temperature in a list from Celsius to Fahrenheit.
- A filter() call uses a lambda to keep only positive numbers from a mixed list.
More examples
Lambda as a sort key
Passes a lambda as the sort key to order a list of dicts by their 'age' value.
users = [{'name': 'Carol', 'age': 28}, {'name': 'Alice', 'age': 34}, {'name': 'Bob', 'age': 22}]
users.sort(key=lambda u: u['age'])
print([u['name'] for u in users])
# Output: ['Bob', 'Carol', 'Alice']Lambda with map()
Applies a conversion lambda to every element in the list using map().
celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: c * 9/5 + 32, celsius))
print(fahrenheit)
# Output: [32.0, 68.0, 98.6, 212.0]Lambda with filter()
Uses filter() with a lambda condition to keep only positive numbers from the list.
numbers = [-5, 0, 3, -1, 8, -2, 7]
positives = list(filter(lambda n: n > 0, numbers))
print(positives) # [3, 8, 7]
Discussion