Search code examples
pythonlistenumerate

Working of Enumerate in Python


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.


Solution

  • enumerate creates a generator function that effectively turns a list of values into a list of tuples.

    L1 = [9, 12, 9, 6]
    

    becomes

    [(0, 9), (1, 12), (2, 9), (3, 6)]
    

    The max function finds the maximum value in that list. If no other arguments were provided to max, it would compare the tuples to each other and this item would be the max - (3, 6). But that's not what we want. We don't want it to use the enumerate number in the comparison.

    max accepts a key argument, which should be a function that takes one argument, which will be the value from the list, and should return a value that will be used to sort the list and choose a maximum. In this case, we want to sort the list based on the second number in each tuple (i.e the 6 in (3, 6)).

    operator.itemgetter is a function that returns a function, which will return an indexed item of the thing it's called on. For example:

    L1 = [3, 4, 6, 2]
    f = operator.itemgetter(0)
    f(L1)
    # 3
    
    f = operator.itemgetter(2)
    f(L1)
    # 6
    

    In this case, it uses operator.itemgetter(1), which is going to return the 6 in (3, 6)

    So the result we get from max(enumerate(l1), key=operator.itemgetter(1)) is a tuple with the index of the max value and the max value in L1.