How to use enumerate() in Python?

Published on Aug. 22, 2023, 12:15 p.m.

enumerate() is a built-in function in Python that allows you to keep track of an element’s position or index while iterating over an iterable object such as a list, tuple or a string.

When you use the enumerate() function, the returned object is an enumerate object, and you can iterate over this object to get the index and value of each element in the iterable object. The enumerate object contains two items for each iteration: the index and the value.

Here is an example:

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

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

This will output:

0 apple
1 banana
2 cherry
3 date

In this example, i is the index that is being tracked, while fruit is the value of each element in the fruits list.

enumerate() is a useful function when you need to track the position of an element in a loop and can simplify code that would otherwise need to use a separate counter variable to keep track of the index.

To iterate over a dictionary in Python using enumerate()

To iterate over a dictionary in Python using enumerate(), you would typically use the items() method to retrieve a list of (key, value) pairs in the dictionary and then pass that list to the enumerate() function to obtain an iterator that yields tuples of the form (index, (key, value)):

person = {'name': 'Alice', 'age': 25, 'city': 'New York'}

for i, (key, value) in enumerate(person.items()):
    print(i, key, value)

This will output:

0 name Alice
1 age 25
2 city New York

In this example, i is the index, key is the key of the current dictionary item being processed, and value is the value associated with that key.

Note that the enumerate() function returns a Tuple where the first element is the index and the second element is the tuple of (key, value) that was retrieved from the original dictionary with the items() method.

To use enumerate() with an open text file in Python

To use enumerate() with an open text file in Python, you can use the readlines() method to read all the lines from the file into a list, and then pass that list to the enumerate() function. Here’s an example:

with open('myfile.txt') as f:
    lines = f.readlines()
    for i, line in enumerate(lines):
        print(i, line)

In this example, myfile.txt is the text file you want to read. The with statement opens the file for reading and ensures that the file is properly closed after the block is executed, even if an exception or error occurs. The readlines() method reads all the lines from the file into a list of strings, and then the enumerate() function is called on that list to obtain an iterator that yields tuples of the form (index, line). The for loop then iterates through this iterator, printing each line along with its index.

Note that the enumerate() function starts the index at 0 by default, but you can specify a different start value by passing a second argument to the enumerate() function. For example, enumerate(lines, start=1) would start the index at 1 instead of 0.

Tags: