Python Lambda
A lambda is a small, anonymous function — one expression, no name, no statements. Use it where a named function would be overkill.
Syntax
PYTHON
square = lambda x: x * x print(square(5)) # 25
That's the same as:
PYTHON
def square(x):
return x * x
Where it actually pays off
Inline functions passed to map, filter, sorted, and friends:
PYTHON
users = [{'name': 'Ada', 'age': 36}, {'name': 'Zed', 'age': 24}]
oldest_first = sorted(users, key=lambda u: -u['age'])
adults = list(filter(lambda u: u['age'] >= 18, users))
names = list(map(lambda u: u['name'], users))
Limits
| Can | Can't |
|---|---|
| Take any args (default, *args, **kwargs) | Have multiple statements |
| Capture surrounding variables | Have annotations or docstrings |
| Be assigned to a name | Use return (the expression IS the return) |
Often a comprehension reads better
PYTHON
names = [u['name'] for u in users] # vs map+lambda
Tip: If your lambda is more than one short expression, give it a name with
def. Code reviewers thank you.Example
Example
square = lambda x: x * x print(square(5)) nums = [1, 2, 3, 4] print(list(map(lambda x: x * 2, nums)))Try it Yourself »
Exercise
Anonymous one-expression function returning x squared.
square =
x: x * x
Six letters; the anonymous-function keyword.
Discussion
Loading…