Ambika Pravin Sonawane
PRO
2 days ago
Ambikacountry asked

What is enumerate in python ?

N
Expert
yesterday
Nisha Sharma answered

Hello! enumerate() is just a simple Python helper that lets you loop through a list and get two things at once:

  1. the index (position) of an element

  2. the value (the actual item) of the element

Example:

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(index, fruit)

Output:

0 apple
1 banana
2 cherry

So instead of manually keeping a counter yourself, Python does it for you.

And I see that you've asked this question based on the code below:

def two_sum(num_list, target_value):
    
    dictionary = {}

    for index, value in enumerate(num_list): 
        # add items of num_list to dictionary
        # value as key and index as value
        dictionary[value] = index
    
    for i in range(len(num_list)):
        complement = target_value - num_list[i]
        
        # check if item's complement is present in dictionary
        if complement in dictionary and dictionary[complement] != i:
            
            # return element index and complement's index
            return [i, dictionary[complement]]
    
num_list = [2, 7, 11, 15]
target_value = 9

result = two_sum(num_list, target_value)
print(result)   

In the two_sum() function, enumerate(num_list) is used because you need both the number and where it sits in the list (its index) to store and return the answer.

Hope that helps. Feel free to ping if you need more help or have any more questions.

Python
This question was asked as part of the Complexity Calculation course.