Home › Learn › Python › Lists

Sorting

Lesson 20 of 40. Order items by any rule with sorted() and key=.

sorted(items) returns a new sorted list; items.sort() sorts the list in place and returns None (a classic mistake is x = items.sort()). Both take reverse=True for descending order and key= to say what to sort by: key=len sorts by length, key=str.lower ignores case, and a lambda builds any rule.

When the key returns a tuple, Python compares the first element, then the second on ties, and so on. key=lambda w: (len(w), w) sorts by length and alphabetically within the same length. min and max accept the same key=.

names = ["bob", "Alice", "eve"]
print(sorted(names))                 # ['Alice', 'bob', 'eve']
print(sorted(names, key=str.lower))  # ['Alice', 'bob', 'eve']
print(sorted([3, 1, 2], reverse=True))

Your task

Write by_length(words) returning the words sorted by length, alphabetically among equal lengths, and longest_words(words, n) returning the n longest words, longest first and alphabetical among equal lengths (all of them, if there are fewer than n).

Part of the final project. longest_words picks the longest words for the report, longest first and alphabetical among ties. It is saved in this browser and loaded into Project: text statistics when you get there.

Hint 1

sorted(words, key=lambda w: (len(w), w))

Hint 2

A negative length sorts longest first while the word itself still sorts alphabetically: sorted(words, key=lambda w: (-len(w), w))[:n]

Show the solution
def by_length(words):
    return sorted(words, key=lambda w: (len(w), w))


def longest_words(words, n):
    return sorted(words, key=lambda w: (-len(w), w))[:n]

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.