iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

CanCan't
Take any args (default, *args, **kwargs)Have multiple statements
Capture surrounding variablesHave annotations or docstrings
Be assigned to a nameUse 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

Test yourself

Q1. lambda may contain…
Q2. A common use is as a key= for…
Q3. For multi-line callbacks use…

Discussion

Loading…