I'm new to Python and I'm currently solving questions to improve my coding skills. I came across the question where I to find the maximum value in a List
and it's corresponding value in an other List
with the same index
number of the maximum value.
for example:
I have two Lists
with values L1 = [9, 12, 9 ,6]
and L2 = [2, 3, 4, 5]
I have to find the maximum value in the List L1
and the index of the maximum value should be used in List L2
to find it's corresponding value.
Max value in List L1 - 12
Index of the max value - 1
print L2[1] -> 3
So to achieve the above logic, I have re-searched a way and obtained it. But I'm not able to understand how the logic is working.
import operator
index, value = max(enumerate(l1), key=operator.itemgetter(1))
print value,
print l2[index]
OUTPUT: 12 3
To understand how the above function is working, I tried to print each section separately but still not able to understand how the logic is working.
print l1 - [9, 12, 9 , 6]
print l2 - [2, 3, 4, 5]
print list(enumerate(l1)) - [<0, 9>, <1, 12>, <2, 9>, <3, 6>]
print list(enumerate(l2)) - [<0, 2>, <1, 3>, <2, 4>, <3, 5>]
print max(enumerate(l1)) - <3, 6>
print max(enumerate(l2)) - <3, 5>
Please help me in understanding how the enumerate
function and key=operator.itemgetter(1))[0]
is working in the above logic. Thanks in advance. Your help is much appreciated.