Chapters
Python114 chapters

Exercises

Lambda

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Sort the people by age using a lambda as the key.

Python
people = [("Ada", 36), ("Grace", 45), ("Katherine", 28)]
# print them sorted by age
Exercise 2

Rewrite the map and filter as comprehensions, with no lambda at all.

Python
numbers = [1, 2, 3, 4]
print(list(map(lambda n: n * n, numbers)))
print(list(filter(lambda n: n % 2 == 0, numbers)))
Exercise 3

All three functions return 2. Capture the loop value so they return 0, 1 and 2.

Python
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])