Intermediate Python · Lesson 3 of 14
Lambda, map, filter and sorted
Write small one-line functions with lambda and use them with sorted, min, max, map and filter to sort and transform data by any rule.
Some functions are so short that giving them a full def feels heavy. A lambda is a one-line function with no name: lambda x: x * 2 takes x and returns x * 2. Its body must be a single expression, with no return keyword.
add_vat = lambda price: round(price * 1.2, 2)
print(add_vat(10))
def add_vat_def(price):
return round(price * 1.2, 2)
print(add_vat_def(10))12.0 12.0
Both do the same. Storing a lambda in a name works, but a def is clearer for that; lambdas shine when passed straight into another function.
Sorting by any rule with key
sorted() and list.sort() accept a key function. Python calls it once for every item and sorts by what it returns. The items themselves are not changed.
names = ["olga", "Ben", "amir", "Chloe"]
print(sorted(names))
print(sorted(names, key=str.lower))
print(sorted(names, key=len))
people = [("Mia", 34), ("Tom", 27), ("Ana", 34), ("Raj", 19)]
print(sorted(people, key=lambda p: p[1]))
print(sorted(people, key=lambda p: (-p[1], p[0])))['Ben', 'Chloe', 'amir', 'olga']
['amir', 'Ben', 'Chloe', 'olga']
['Ben', 'olga', 'amir', 'Chloe']
[('Raj', 19), ('Tom', 27), ('Mia', 34), ('Ana', 34)]
[('Ana', 34), ('Mia', 34), ('Tom', 27), ('Raj', 19)]Capital letters sort before small ones, so str.lower gives a natural order. A tuple key sorts by age (largest first, thanks to the minus) and then by name.
The same key works with min() and max(), so you can find the cheapest or the longest item in one line.
products = [
{"name": "Lamp", "price": 24.0},
{"name": "Mug", "price": 6.5},
{"name": "Chair", "price": 49.9},
]
cheapest = min(products, key=lambda p: p["price"])
print(cheapest["name"])
by_price = sorted(products, key=lambda p: p["price"], reverse=True)
print([p["name"] for p in by_price])Mug ['Chair', 'Lamp', 'Mug']
map and filter
map() applies a function to every item; filter() keeps only the items for which a function returns True. Both give back a lazy object that produces items on demand, so wrap it in list() to see the results.
celsius = [18, 22, 30, 15]
fahrenheit = list(map(lambda c: c * 9 / 5 + 32, celsius))
print(fahrenheit)
warm = list(filter(lambda c: c >= 20, celsius))
print(warm)
prices = ["4.50", "12", "0.99"]
print(list(map(float, prices)))[64.4, 71.6, 86.0, 59.0] [22, 30] [4.5, 12.0, 0.99]
[c * 9 / 5 + 32 for c in celsius]. Many Python programmers find comprehensions easier to read, and the next lesson covers them. map is handy when the function already exists, like map(float, prices).✎ Exercise
Sort the products by price, cheapest first, and by name when prices are equal, and print the sorted list. Then print a list with only the names of the products that cost less than 10, in that sorted order.
Hint: Use a tuple key (price, name). Then filter with a lambda that checks p[1] < 10.
products = [("Pen", 2.5), ("Book", 12.0), ("Bag", 9.5), ("Cup", 2.5), ("Hat", 15.0)]
# your code here
Expected output:
[('Cup', 2.5), ('Pen', 2.5), ('Bag', 9.5), ('Book', 12.0), ('Hat', 15.0)]
['Cup', 'Pen', 'Bag']Show a solution
products = [("Pen", 2.5), ("Book", 12.0), ("Bag", 9.5), ("Cup", 2.5), ("Hat", 15.0)]
ordered = sorted(products, key=lambda p: (p[1], p[0]))
print(ordered)
cheap = filter(lambda p: p[1] < 10, ordered)
print([name for name, price in cheap])[('Cup', 2.5), ('Pen', 2.5), ('Bag', 9.5), ('Book', 12.0), ('Hat', 15.0)]
['Cup', 'Pen', 'Bag']Check yourself
1. What does sorted(words, key=len) sort by?
The key function len is called on each word, and the words are sorted by those lengths.
2. What does list(filter(lambda n: n % 2 == 0, [1, 2, 3, 4])) give?
filter keeps only the items where the function returns True: the even numbers.
3. Which line is a valid lambda?
A lambda's body is a single expression and has no return keyword.