Exercises
Lambda
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Sort the people by age using a lambda as the key.
Python
people = [("Ada", 36), ("Grace", 45), ("Katherine", 28)]
# print them sorted by age
The key takes one item and returns the part to sort on.
people = [("Ada", 36), ("Grace", 45), ("Katherine", 28)]
print(sorted(people, key=lambda person: person[1]))Exercise 2Passed
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)))A comprehension reads left to right and needs no lambda.
numbers = [1, 2, 3, 4]
print([n * n for n in numbers])
print([n for n in numbers if n % 2 == 0])Exercise 3Passed
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])A default argument is evaluated at definition time.
funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])