Python Arena
Step 4 of 6

Sorting: sort and sorted

The sort method puts the items of a list in order, from smallest to greatest. Strings are sorted in alphabetical order:

scores = [12, 30, 7, 18]
scores.sort()
print(scores)
names = ["Linus", "Ada", "Grace"]
names.sort()
print(names)
Output
[7, 12, 18, 30]
['Ada', 'Grace', 'Linus']

sort changes the list itself: the original order is gone. When you still need the original, use the function sorted instead. It doesn't touch the list you give it, but returns a new, sorted list:

arrivals = ["Linus", "Ada", "Grace"]
alphabetical = sorted(arrivals)
print(arrivals)
print(alphabetical)
Output
['Linus', 'Ada', 'Grace']
['Ada', 'Grace', 'Linus']

So arrivals still says who came first, and alphabetical is a sorted copy.

For the order from greatest to smallest, sort the list and then turn it around with the reverse method, which reverses the order of any list:

scores = [12, 30, 7, 18]
scores.sort()
scores.reverse()
print(scores)
Output
[30, 18, 12, 7]

A common mistake

sort changes the list and returns nothing, that is, None. Storing what it returns gives you None and not the sorted list:

scores = [12, 30, 7]
ordered = scores.sort()
print(ordered)
print(scores)
Output
None
[7, 12, 30]

Either sort the list itself with scores.sort() and keep using scores, or make a sorted copy with ordered = sorted(scores). The same goes for append, insert and remove: they change the list and return None, so scores = scores.append(5) loses the whole list.

Capital letters

In alphabetical order, Python puts every capital letter before every small letter, so "Zebra" comes before "apple":

In the Python interpreter
>>> sorted(["banana", "Zebra", "apple"])
['Zebra', 'apple', 'banana']

Write the strings in the same case when you want a normal alphabetical order.

Your task

Challenge 1 of 3

The program should print the scores in the order they were given and then from smallest to greatest, but the second line prints None. Fix it so it prints:

[12, 30, 7, 18]
[7, 12, 18, 30]

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

Write a program that reads exam scores (whole numbers) until the user types an empty line. Then it prints the scores in order from lowest to highest, the lowest score and the highest score:

Score: 15
Score: 9
Score: 20
Score:
[9, 15, 20]
Lowest: 9
Highest: 20

You can assume the user types at least one score.