In the lambda function lambda tup: tup[1]
, tup refers to the element of list data
, and tup[1]
refers to the second element of the item.
When you pass this to sorted function, you tell it to use the second element of the item in the list as a comparison key, so the result you get is the sorted list on the second element
From the docs
key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).
Hence the behaviour is as follows
In [54]: data = [[4,5,6], [1,2,3], [7,8,9]]
In [55]: sorted_by_second = sorted(data, key=lambda tup: tup[1])
In [56]: sorted_by_second
Out[56]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Note that you can also use operator.itemgetter to do the same thing, which automatically picks the second element from the tuple
In [60]: import operator
In [64]: data = [[4,5,6], [1,2,3], [7,8,9]]
In [65]: sorted_by_second = sorted(data, key=operator.itemgetter(1))
In [66]: sorted_by_second
Out[66]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]