Secrets About Python Enumerate

by:

Python

Python Enumerate command was unknown to me for a long time. On this recipe, you will learn how to use it when using a for loop on a list, dictionary, and a set which is one of the most useful calls in Python.

What is Enumerate? Using enumerate in a Python list

Frequently, I loop into a list or dictionary and want to keep track of the loop iteration count. This task can be naively accomplished using a counter:

my_list = ["San Diego", "New York", "Santa Barbara", "Miami"]

counter = 0
for city_name in my_list:
    print(city_name, counter)
    counter += 1

Which prints as:

>>> San Diego 0
>>> New York 1
>>> Santa Barbara 2
>>> Miami 3

However, this task can be simply accomplished using the function enumerate:

my_list = ["San Diego", "New York", "Santa Barbara", "Miami"]

for counter, city_name in enumerate(my_list):
    print(city_name, counter)

which prints the same message as before:

>>> San Diego 0
>>> New York 1
>>> Santa Barbara 2
>>> Miami 3

Setting a Start Point

By default the index value from which the counter is to be started as 0. This can be changed to whatever you want.

my_list = ["San Diego", "New York", "Santa Barbara", "Miami"]

for counter, city_name in enumerate(my_list,1):
    print(city_name, counter)

which prints the same message as before:

>>> San Diego 1
>>> New York 2
>>> Santa Barbara 3
>>> Miami 4

Using enumerate in a Python dictionary

Last but not least, we can also use enumerate in a Python dictionary. When looping through a dictionary.

my_hash_table = {}
my_hash_table['San Diego'] = 'USA'
my_hash_table['San Francisco'] = 'USA'
my_hash_table['Shanghai'] = 'China'
my_hash_table['Tokyo'] = 'Japan'

for counter, city_name in enumerate(my_hash_table, 1):
    country_name = my_hash_table[city_name]
    print(counter, city_name, country_name)

which should print:

>>> 1 San Diego USA
>>> 2 San Francisco USA
>>> 3 Shanghai China
>>> 4 Tokyo Japan

In conclusion, I hope you can see how the function enumerates is useful. I frequently use it when I need to enumerate files and display their order in the log file.

More Resources

Here are three of my favorite Python Books in case you want to learn more about it.

Related Posts