Lambda, map and filter
Small functions inline, and when a loop is clearer.
🎬 Video version coming soon — read it now
A lambda is a tiny, unnamed function written in one expression. It's most useful as the key for sorting and grouping.
Lambda syntax
double = lambda x: x * 2
print(double(5)) # 10This is the same as:
def double(x):
return x * 2Assigning a lambda to a name like this is considered poor style; just use def. Lambdas shine when you pass a small function directly to another function.
The best use: sort keys
students = [("Anil", 8.4), ("Bhavana", 9.1), ("Chaitanya", 7.2)]
by_cgpa = sorted(students, key=lambda s: s[1], reverse=True)
by_name_length = sorted(students, key=lambda s: len(s[0]))
top = max(students, key=lambda s: s[1])key tells sorted, min and max what to compare. For dictionaries: key=lambda d: d["cgpa"].
operator.itemgetter: often cleaner
from operator import itemgetter, attrgetter
sorted(students, key=itemgetter(1)) # same as lambda s: s[1]
sorted(rows, key=itemgetter("branch", "cgpa")) # sort by two keys
sorted(accounts, key=attrgetter("balance")) # for objectsmap and filter
prices = [100, 250, 400]
with_gst = list(map(lambda p: p * 1.18, prices))
expensive = list(filter(lambda p: p > 200, prices))map applies a function to every item; filter keeps items where the function returns True. Both return lazy iterators, hence the list().
Usually, comprehensions are clearer
with_gst = [p * 1.18 for p in prices]
expensive = [p for p in prices if p > 200]Most Python developers prefer comprehensions over map/filter with lambdas. map is still neat when you already have a named function: list(map(str.upper, names)) or list(map(int, "1 2 3".split())).
Lambda limits
- One expression only: no statements, no assignments, no loops
- No docstring, and the name in error messages is just
<lambda>
If you need more, write a normal function.
sorted(..., key=...) with lambda or itemgetter covers about 90% of real lambda use. Master that and you're set.In one line
Use lambda for small inline functions, especially sort keys; prefer comprehensions over map and filter, and def for anything bigger.
Share with a friend