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)
[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)
['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)
[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)
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":
>>> sorted(["banana", "Zebra", "apple"])
['Zebra', 'apple', 'banana']Write the strings in the same case when you want a normal alphabetical order.