2

I want to find the max element's index in a list of tuple elements so i can reach the key value. How can i do that? Basically my code;

temp_tuple = [
    ('A', 1),
    ('B', 3),
    ('C', 1)
]

max_value = max(value[1] for value in temp_tuple)

I want to find ('B',3) or 1 as index

Sevval Kahraman
  • 1,185
  • 3
  • 10
  • 37
  • Does this answer your question? https://stackoverflow.com/questions/13145368/find-the-maximum-value-in-a-list-of-tuples-in-python – ptts May 05 '21 at 11:41

2 Answers2

4

If you want only max tuple value:

max_tuple = max(temp_tuple, key=lambda x:x[1])
print(max_tuple)

>> ('B', 3)

if you want index of max tuple too:

max_tuple = max(temp_tuple, key=lambda x:x[1])
max_tuple_index = temp_tuple.index(max_tuple)
print(max_tuple)
print(max_tuple_index)

>> ('B', 3)
>> 1
Hamza usman ghani
  • 2,264
  • 5
  • 19
2
temp_tuple = [("A", 1), ("B", 3), ("C", 1)]

sorted_temp_tuple = sorted(enumerate(temp_tuple), key=lambda i: i[1][1], reverse=True)
# Result: [(1, ('B', 3)), (0, ('A', 1)), (2, ('C', 1))]

original_index, max_val_item = sorted_temp_tuple[0]

print(max_val_item)
>> ('B', 3)

print(original_index)
>> 1
ptts
  • 1,848
  • 6
  • 14
  • 2
    you marked this question for a dupe, then later give an answer to it, could have left a comment instead – python_user May 05 '21 at 11:50
  • 1
    True, at first I didn't think about OP's request to receive both the value *and* the index. – ptts May 05 '21 at 11:52