Python Fundamentals ยท Functions

lambda, map, filter and sorted

Small throwaway functions for sorting by a key, changing every item, and keeping some items.

lambdas.py

people = [("ana", 31), ("ben", 25), ("cara", 28)]

by_age = sorted(people, key=lambda p: p[1])          # sort by the second item
names = list(map(lambda p: p[0].title(), people))    # change every item
over_26 = list(filter(lambda p: p[1] > 26, people))  # keep some items
oldest = max(people, key=lambda p: p[1])
print(by_age)
print(names, over_26, oldest)

Step by step

  1. People as (name, age) tuples.
  2. key=lambda p: p[1] tells sorted to compare people by age. The lambda runs once per person.
  3. Line runs: by_age = sorted(people, key=lambda p: p[1]) # sort by the second item.
  4. p now points to a different tuple: ['ben', 25].
  5. Line runs: by_age = sorted(people, key=lambda p: p[1]) # sort by the second item.
  6. p now points to a different tuple: ['cara', 28].
  7. Line runs: by_age = sorted(people, key=lambda p: p[1]) # sort by the second item.
  8. <lambda>() has finished, so its names are gone. The value it returned, [a tuple, a tuple, a tuple], is stored in by_age.
  9. map runs the lambda on every item: names in title case.
  10. Line runs: names = list(map(lambda p: p[0].title(), people)) # change every item.
  11. p now points to a different tuple: ['ben', 25].
  12. Line runs: names = list(map(lambda p: p[0].title(), people)) # change every item.
  13. p now points to a different tuple: ['cara', 28].
  14. Line runs: names = list(map(lambda p: p[0].title(), people)) # change every item.
  15. <lambda>() has finished, so its names are gone. The value it returned, ['Ana', 'Ben', 'Cara'], is stored in names.
  16. filter keeps the items where the lambda returns True.
  17. Line runs: over_26 = list(filter(lambda p: p[1] > 26, people)) # keep some items.
  18. p now points to a different tuple: ['ben', 25].
  19. Line runs: over_26 = list(filter(lambda p: p[1] > 26, people)) # keep some items.
  20. p now points to a different tuple: ['cara', 28].
  21. Line runs: over_26 = list(filter(lambda p: p[1] > 26, people)) # keep some items.
  22. <lambda>() has finished, so its names are gone. The value it returned, [a tuple, a tuple], is stored in over_26.
  23. max also accepts key=: the person with the highest age.
  24. Line runs: oldest = max(people, key=lambda p: p[1]).
  25. p now points to a different tuple: ['ben', 25].
  26. Line runs: oldest = max(people, key=lambda p: p[1]).
  27. p now points to a different tuple: ['cara', 28].
  28. Line runs: oldest = max(people, key=lambda p: p[1]).
  29. <lambda>() has finished, so its names are gone. The value it returned, ['ana', 31], is stored in oldest.
  30. It prints [('ben', 25), ('cara', 28), ('ana', 31)].
  31. lambda makes a one-line function on the spot, perfect for telling sorted, max, map and filter what to look at.