August 2018
Intermediate to advanced
366 pages
10h 14m
English
A very common approach to sorting is to keep a list of entries in a tuple, where the first element is key for which we are sorting and the second element is the value itself.
For a scoreboard, we can keep each player's name and how many points they got:
scores = [(123, 'Alessandro'),
(143, 'Chris'),
(192, 'Mark']
Storing those values in tuples works because comparing two tuples is performed by comparing each element of the first tuple with the element in the same index position in the other tuple:
>>> (10, 'B') > (10, 'A') True >>> (11, 'A') > (10, 'B') True
It's very easy to understand what's going on if you think about strings. 'BB' > 'BB' is the same as ('B', 'B') > ('B', 'A'); in the end, a string is just a list of characters. ...