Lesson 4 of 5 · Functions · 2 min read · Updated

Lambda, map and filter

Tiny unnamed functions, and passing a function to another function.

In Python a function is a value like any other: you can store it, pass it and return it. A lambda is a one-expression function without a name, written right where it is needed.

python
square = lambda n: n * n
print(square(6))

students = [("Priya", 87), ("Arun", 73), ("Meena", 94)]
by_marks = sorted(students, key=lambda s: s[1], reverse=True)
print(by_marks[0])
print(min(students, key=lambda s: s[1]))
Output
36
('Meena', 94)
('Arun', 73)

The everyday use is key=: sorted(), min() and max() call your lambda on each item and compare what it returns. Here that is the marks, so the students are ordered by marks rather than by name.

map and filter

python
marks = [72, 45, 91, 38]
print(list(map(lambda m: m + 5, marks)))
print(list(filter(lambda m: m >= 50, marks)))

# The same with comprehensions:
print([m + 5 for m in marks])
print([m for m in marks if m >= 50])
Output
[77, 50, 96, 43]
[72, 91]
[77, 50, 96, 43]
[72, 91]

map applies a function to every item; filter keeps the items for which it returns true. Both give back a lazy object, hence list(). Most Python programmers prefer the comprehension versions — they say the same thing more plainly.

Note

A lambda can hold only a single expression — no loops, no statements. Giving one a name, as with square above, is only for illustration; if it deserves a name, write it with def.

What does sorted(["bb", "a", "ccc"], key=len) return?

Try this now

  1. Sort a list of (city, population) tuples by population, largest first.
  2. From a list of names, find the longest one with max(..., key=len).

Create a free account to save your progress, or sign in.