Getting the maximum value of element tuple in list of tuples

Viewed 695

I have this code:

vals = [(1,3,5),(2,2,5),(1,2,6)]
max(vals ,key=itemgetter(1))[2]

My question is: why does it return 5 instead of 6 ? I need the maximum value of the last element. If I take max(...)[0] it gives 2, if I take max(...)[1] it gives 3, but if I take max(...)[2] it gives 5. Why is this?

5 Answers

By keying with itemgetter(1), you're asking Python to take the maximum tuple based on the values of the 1th element. (1,3,5) has the biggest element in the 1th index (i.e. 3). Then you access the 2nd index from that tuple (i.e. 5).

To take the maximum value of the last element, use this instead:

>>> max([c for a,b,c in vals])
6

key=itemgetter(1) means that max checks the second element of the tuple to determine which tuple is the "max" tuple.

So it picks the first tuple since 3 is higher than 2, then you pick the last value and you get 5

If you want 6, I guess you could do max(vals ,key=itemgetter(2))[2]

But you could also get the values of index 2 and perform the max like this:

max(map(itemgetter(2),vals))

since you're discarding the other values

If you want the last element, just say so by using the index -1 in your code. In your code, the 1 picks the second element of each tuple for comparison in max and the 2 is unnecessarily hardcoding the knowledge that your tuples have length three.

>>> vals = [(1,3,5),(2,2,5),(1,2,6)]
>>> max(vals, key=itemgetter(-1))[-1]
>>> 6

x[2] is the 3 element of tuple on which max should be calculated and [2] is the third element of max tuple calculated

max(vals ,key=lambda x:x[2])[2]

or

max(vals ,key=itemgetter(2))[2] # you were using itemgetter(1) which would be second element of the tuple

If I'm passing an index I do this:

vals = [(1,3,5),(2,2,5),(1,2,6)]
max(vals[2])
#> 6
Related