Technical

What is python enumerate() function?

green and white line illustration

The enumerate() function in Python is a built-in function that allows us to iterate over a sequence (such as a list, tuple, or string) while keeping track of the index of the current item. It returns both the index and the value of each item in the sequence as you iterate through it.

Here’s a simple example to illustrate how enumerate() works:

# python



# Example list
fruits = ['apple', 'banana', 'orange', 'grape']

# Using enumerate to iterate over the list with index and value
for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Value: {fruit}")



When we use enumerate(), the function gives us back two loop variables:

  1. The index of the current iteration
  2. The fruit of the item at the current iteration

Just like with a normal python for loop, the loop variables can be named whatever we want.

So our terminal output will be:



Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange
Index: 3, Value: grape


In this example:

  • The enumerate(fruits) function is used to iterate over the fruits list.
  • The for loop unpacks each tuple returned by enumerate() into index and fruit.
  • Inside the loop, we can then use index to get the index of the current item and fruit to get the value of the current item.

The enumerate() function can also take an optional second argument, which specifies the starting value of the index. By default, the index starts from 0 (as we know, classic python indexing)

Here’s an example using a different starting index:

# python

fruits = ['apple', 'banana', 'orange', 'grape']

# Using enumerate with a starting index of 1
for index, fruit in enumerate(fruits, start=1):
    print(f"Index: {index}, Value: {fruit}")

In this case, our terminal output will be:


Index: 1, Value: apple  
Index: 2, Value: banana
Index: 3, Value: orange
Index: 4, Value: grape

Now let’s consider a more complex example where we have a list of words, and we want to create a dictionary that maps each word to its length. We’ll use enumerate() to do this:

# python

# Example list of words
words = ['apple', 'banana', 'orange', 'grape']

# Using enumerate to create a dictionary mapping words to their lengths
word_lengths = {word: len(word) for word in words}

print("Original list of words:", words)
print("Dictionary mapping words to lengths:", word_lengths)

output:


Original list of words: ['apple', 'banana', 'orange', 'grape']
Dictionary mapping words to lengths: {'apple': 5, 'banana': 6, 'orange': 6, 'grape': 5}

In this example:

  • We use a dictionary comprehension to create a new dictionary (word_lengths) where each word is a key, and the corresponding value is the length of that word.
  • The enumerate() function is not used explicitly in this example, but it indirectly plays a role when iterating over the words list with the for word in words loop. The loop iterates over each word in the list, and the len(word) part retrieves the length of each word.

Now, let’s modify the example to include the index of each word in the original list using enumerate():

# python

# Example list of words
words = ['apple', 'banana', 'orange', 'grape']

# Using enumerate to create a dictionary mapping words to their lengths with index
word_lengths_with_index = {index: (word, len(word)) for index, word in enumerate(words)}

print("Original list of words:", words)
print("Dictionary mapping index to word and length:", word_lengths_with_index)

so here the output will be:

Original list of words: ['apple', 'banana', 'orange', 'grape']
Dictionary mapping index to word and length: {0: ('apple', 5), 1: ('banana', 6), 2: ('orange', 6), 3: ('grape', 5)}

In this modified example:

  • The enumerate() function is used to get both the index and the word during iteration.
  • The resulting dictionary (word_lengths_with_index) maps the index to a tuple containing the word and its length.

We can use it for far more complex and intricate solution! Please feel free to copy the codes and experiment as you like.

To know more about the enumerate() function, please read the official documentation here.

Happy coding 🙂

Tagged

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.