Python Fundamentals ยท Functions
Small throwaway functions for sorting by a key, changing every item, and keeping some items.
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)key=lambda p: p[1] tells sorted to compare people by age. The lambda runs once per person.by_age = sorted(people, key=lambda p: p[1]) # sort by the second item.p now points to a different tuple: ['ben', 25].by_age = sorted(people, key=lambda p: p[1]) # sort by the second item.p now points to a different tuple: ['cara', 28].by_age = sorted(people, key=lambda p: p[1]) # sort by the second item.<lambda>() has finished, so its names are gone. The value it returned, [a tuple, a tuple, a tuple], is stored in by_age.names = list(map(lambda p: p[0].title(), people)) # change every item.p now points to a different tuple: ['ben', 25].names = list(map(lambda p: p[0].title(), people)) # change every item.p now points to a different tuple: ['cara', 28].names = list(map(lambda p: p[0].title(), people)) # change every item.<lambda>() has finished, so its names are gone. The value it returned, ['Ana', 'Ben', 'Cara'], is stored in names.over_26 = list(filter(lambda p: p[1] > 26, people)) # keep some items.p now points to a different tuple: ['ben', 25].over_26 = list(filter(lambda p: p[1] > 26, people)) # keep some items.p now points to a different tuple: ['cara', 28].over_26 = list(filter(lambda p: p[1] > 26, people)) # keep some items.<lambda>() has finished, so its names are gone. The value it returned, [a tuple, a tuple], is stored in over_26.oldest = max(people, key=lambda p: p[1]).p now points to a different tuple: ['ben', 25].oldest = max(people, key=lambda p: p[1]).p now points to a different tuple: ['cara', 28].oldest = max(people, key=lambda p: p[1]).<lambda>() has finished, so its names are gone. The value it returned, ['ana', 31], is stored in oldest.[('ben', 25), ('cara', 28), ('ana', 31)].