pairs
is a list of tuples. (1, 'one')
is an example of a tuple with two elements.
From the docs:
Tuples are immutable sequences, typically used to store collections of heterogeneous data
We then sort that list in-place on the 2nd element of the tuple via key=lambda pair: pair[1]
(pair[1]
signifies that the sorting key should be the 2nd element of the tuple)
Since the second element is a string, the sort is done lexicopgraphically, or alphabetically.
From the docs:
list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
In [7]: pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
In [8]: pairs.sort(key=lambda pair: pair[1])
In [9]: pairs
Out[9]: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
If you sort on the first element of the tuple, the sort is done on the integers and is done numerically
In [10]: pairs.sort(key=lambda pair: pair[0])
In [11]: pairs
Out[11]: [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
This questions here goes in more details about what a tuple is and
this question here goes in more details about how key
works in sorting functions sort()
and sorted()