Sorting with key

sorted returns a new sorted list. Its key argument tells Python which value to compare for each item when it sorts.

files = ["notes.txt", "app.py", "README.md"]

print(sorted(files))
print(sorted(files, key=len))
print(sorted(files, key=str.lower))

Output:

['README.md', 'app.py', 'notes.txt']
['app.py', 'notes.txt', 'README.md']
['app.py', 'notes.txt', 'README.md']

A plain sorted puts README.md first, because Python puts the capital letters A to Z before the lowercase letters a to z. key=len sorts by length. key=str.lower compares the lowercase version of each string, but the list you get back still has the original strings.

Notice that you write len and str.lower without parentheses. You do not call them yourself. sorted calls them on each item for you.

The sort is stable. This means that items with equal keys stay in the order they had before. notes.txt and README.md both have 9 characters, so in the second line they keep their original order.

To sort records by one field, use a lambda as the key. Here the lambda gives each person's age, so the team is sorted by age:

team = [
    {"name": "Maya", "age": 34},
    {"name": "Leo", "age": 27},
    {"name": "Noah", "age": 41},
]
ordered = sorted(team, key=lambda person: person["age"])
for person in ordered:
    print(person["name"], person["age"])

Output:

Leo 27
Maya 34
Noah 41

Add reverse=True to any of these calls to get the opposite order.

In the exercise, sort the words in each of the three ways the task asks for.