Sorting lists temporarily
Consider the following list of surnames:
last_names = ['Jones', 'Antunovich', 'Daniels', 'Thomson']
Let’s print the list:
print(last_names)
['Jones', 'Antunovich', 'Daniels', 'Thomson']
Wouldn’t it be nice to sort the names in alphabetical order? This is where the sorted() function comes into play. We simply need to call this function and pass it our list as the argument:
print(sorted(last_names))
>>>
['Antunovich', 'Daniels', 'Jones', 'Thomson']
>>>
To sort in reverse alphabetical order, we can use the reverse=True argument:
print(sorted(last_names, reverse=True))
>>>
['Thomson', 'Jones', 'Daniels', 'Antunovich']
>>>
The important thing about the sorted() function is that the list is sorted only temporarily – the original order of elements is not modified, as seen in the example below:
print(sorted(last_names))
print(last_names[0])
>>>
['Antunovich', 'Daniels', 'Jones', 'Thomson']
Jones
>>>