PythiloLesson 22 of 30 · progress kept in this browser

Sorting with key and lambda

sorted, min and max accept key: a function applied to each item, whose result is compared instead of the item itself.

words = ["kiwi", "Fig", "banana"]
print(sorted(words))          # Fig first
print(sorted(words, key=str.lower))
print(max(words, key=len))    # banana

people = [("ada", 36), ("alan", 41)]
oldest = max(people, key=lambda p: p[1])
print(oldest)  # ('alan', 41)

lambda args: expression makes a small unnamed function. Use it where a function is needed only once.

Your task

Write rank(players) that takes (name, score) tuples and returns a new list sorted by score, highest first, with equal scores ordered by name from A to Z. Write longest_word(words) returning the longest word, the first one on ties, or None for an empty list.