I have a list of tuples of the form:
[(0, 1), (2, 3), (4, -5), (6, -3)]
I want to sort this list by the second value of each tuple (that is, in case we would have [(4, -5), (6, -3), (0, 1), (2, 3)]
. How to do that?
I have a list of tuples of the form:
[(0, 1), (2, 3), (4, -5), (6, -3)]
I want to sort this list by the second value of each tuple (that is, in case we would have [(4, -5), (6, -3), (0, 1), (2, 3)]
. How to do that?
The simplest way is to use key
in calling the sort
method of the list:
data = [(0, 1), (2, 3), (4, -5), (6, -3)]
data.sort(key=lambda x: x[1])
>>> data
[(4, -5), (6, -3), (0, 1), (2, 3)]
In this way, the 1
element of each tuple will be the sort key. Another option (considered faster ) is to use the itemgetter
function of the operator
library.