TL ; DR:
To sort by your own rule, give sorted a key. The key is a small function. It says what to sort each item by.
nums = [25, 13, 5, 41, 33]
print(sorted(nums, key=lambda n: (n % 10, n)))
# [41, 13, 33, 5, 25]
scores = [70, 95, 82]
print(sorted(scores, key=lambda s: -s))
# [95, 82, 70]
Full lesson:
You met sorted in the Shopping Cart project. It puts numbers from small to large and text from A to Z. Sometimes you need another order. The shortest word may have to come first, or the highest score.
For that, give sorted a key. The key is a small function. The sorted function calls it on every item. Then it sorts the items by what the key returned.
The function lambda w: len(w) is written in one line. It has no name. It gets one value, w, and returns len(w). It works like a def function with only a return line.
- To sort by length, use
key=lambda w: len(w). - For two rules, the key returns a tuple. With
key=lambda n: (n % 10, n), each number gives its last digit, then itself. Tuples are compared item by item. So the numbers go by last digit first. Numbers with the same last digit then go from small to large. - To sort from high to low, use
key=lambda s: -s. The biggest number has the smallest-s, so it comes first. - For plain numbers,
sorted(scores, reverse=True)also sorts from high to low.
The sorted function makes a new list. The old list stays as it was.
The list method lst.sort(key=...) sorts the list itself instead. It returns None. So never write lst = lst.sort().
Your task
A pet shop sells toys. Their prices are in prices. Make a list named highFirst with the prices from high to low.
The shop's pets are in names. Make a list named byLastLetter with the names sorted by their last letter, in alphabetical order. Names with the same last letter go from A to Z.
The code already prints both, one item per line.
Expected output:
30
12
8
5
Bella
Luna
Bo
Coco
Max
RexFree plan: 30 tutor messages. PRO is unlimited.
