Learn about Python enumerate function or enumerate in Python programming.

Most often we code programs involving lists. If we need a number from the list, we need to iterate. Moreover, we need a way to keep track of which particular iteration we are in currently.

We usually find ourselves using a for loop to iterate over the list. One way of doing this is to declare an index variable and increment the index within the loop.

However, we have a better alternative – the Python enumerate function.

In this tutorial, we will discuss Enumerate in Python Programming:

  • Manually keeping track of an index in a loop without enumerate()
  • What enumerate() does
  • How to call enumerate() with a different start value
  • Iterating over enumerate objects created from lists
  • How to create enumerate objects from tuples
  • Enumerate characters in a string using enumerate()

Usual way: Iterate over a list using an index and a for loop

This example uses a for loop to iterate over a list, and an index variable to keep track of the position of each item as it is iterated over. This will help us to print out not only the current item but also its position.


primes = [2, 3, 5, 7, 11, 13, 17, 19]
index = 0

for prime in primes:
    print(f"primes[{index}] = {prime}")

The loop prints out the prime numbers in the list, as the following output shows.

Output

primes[0] = 2
primes[0] = 3
primes[0] = 5
primes[0] = 7
primes[0] = 11
primes[0] = 13
primes[0] = 17
primes[0] = 19

However, there is a problem; we forgot to update the index each time the loop body was executed. To correct this, we need to add an increment to the index variable after the print function.


primes = [2, 3, 5, 7, 11, 13, 17, 19]
index = 0

for prime in primes:
    print(f"primes[{index}] = {prime}")

    # we make sure we increment index
    index += 1

Output:

primes[0] = 2
primes[1] = 3
primes[2] = 5
primes[3] = 7
primes[4] = 11
primes[5] = 13
primes[6] = 17
primes[7] = 19

The above example shows the problem with manually incrementing a variable to keep track of an iteration; we could easily forget to do the increment, especially when we have a lot of code within the loop. Fortunately, Python has provided a way to eliminate this kind of bug by way of the enumerate() function.

Better way : Using enumerate() Function in Python

Python’s enumerate() function can help us enumerate, or create count information for, each item in a list. The syntax is

enumerate(iterable, start=start_value)

where:
iterable is either a list, a tuple, or a string
start is the value to start counting from

enumerate() returns an object of type enumerate. When converted to a list, each item in the list is a tuple having the form (count, iterable[count]). An example will show how to use enumerate() with a list of continents


continents = ["Asia", "Africa", "North America", "South America", "Antarctica", "Australia", "Europe"]

enum_continents = enumerate(continents)

print(list(enum_continents))

This example makes use of enumerate() to enumerate continents. The result of the call to enumerate() is stored in the variable enum_continents as an enumerate object. Finally, enum_continents is converted into a list to produce the following output

Output:

[(0, 'Asia'), (1, 'Africa'), (2, 'North America'), (3, 'South America'), (4, 'Antarctica'), (5, 'Australia'), (6, 'Europe')]

Call enumerate() with a Different Start Value

By default, the enumerate() parameter, start, has a value of 0. Actually, start can have any integer value apart from zero.

In the next example, we will modify the previous example to make it look like we are specifying a count (the first item is 1, the second item is 2, and so on).

We will do this by specifying a start value of 1.


continents = ["Asia", "Africa", "North America", "South America", "Antarctica", "Australia", "Europe"]

enum_continents = enumerate(continents, start=1)

print(list(enum_continents))

Output:

[(1, 'Asia'), (2, 'Africa'), (3, 'North America'), (4, 'South America'), (5, 'Antarctica'), (6, 'Australia'), (7, 'Europe')]

Iterating Over an Enumerate Object

for loops can iterate over enumerate objects. In the following example, we will use a for loop to iterate over the enumerate object produced by enumerating our continents list.


continents = ["Asia", "Africa", "North America", "South America", "Antarctica", "Australia", "Europe"]

for e in enumerate(continents, start=1):
    print(e)

Each element in the enumerate object is a tuple, as the output shows

Output:

(1, 'Asia')
(2, 'Africa')
(3, 'North America')
(4, 'South America')
(5, 'Antarctica')
(6, 'Australia')
(7, 'Europe')

The convenience provided by the enumerate() function is clearly seen in this example with a for loop. We do not need to explicitly initialize an index variable and increment it within the loop because enumerate() does this for us.

We can rewrite the program to individually keep track of the count and list item, and then use the values to produce a nicer printout


continents = ["Asia", "Africa", "North America", "South America", "Antarctica", "Australia", "Europe"]

for count, continent in enumerate(continents):
    print(f"continent[{count}] = {continent}")     # print it nicer

Output:

continent[0] = Asia
continent[1] = Africa
continent[2] = North America
continent[3] = South America
continent[4] = Antarctica
continent[5] = Australia
continent[6] = Europe

Using Python enumerate() with Tuples

In the previous examples, we have been enumerating only lists. enumerate() can also produce enumerate objects for tuples. The next example will illustrate tuple enumeration


companies = ("Microsoft", "Alibaba", "Verizon", "Facebook", "Google", "Uber")

print("Companies:")

for count, company in enumerate(companies, start=1):
    print(f"{count}) {company}")

The program defined a tuple object containing company names, and then called enumerate() within a for loop to produce the following output:

Output:

Companies:
1) Microsoft
2) Alibaba
3) Verizon
4) Facebook
5) Google
6) Uber

Tuples in Python, like lists, are iterable objects. That is why enumerate() also worked with tuples.

Python enumerate() and Strings

Since a string is also an iterable, enumerate() can also work with strings to enumerate the characters within the string. The next example will show how to use enumerate() with a string.


str_val = "enumerate"

print("characters with their positions in str_val:")
for idx, char in enumerate(str_val):
    print(f"str_val[{idx}] is '{char}'")

The program’s purpose is to print out each character in the variable str_val, along with their index. enumerate() also makes this an easy task, as we see in the output.

Output:

characters with their positions in str_val:
str_val[0] is 'e'
str_val[1] is 'n'
str_val[2] is 'u'
str_val[3] is 'm'
str_val[4] is 'e'
str_val[5] is 'r'
str_val[6] is 'a'
str_val[7] is 't'
str_val[8] is 'e'

Conclusion

We have finally come to the end of the tutorial on the python enumerate() function. This tutorial covered how to make use of enumerate() to number the elements in lists, tuples and strings. We hope this tutorial will be of help to you in your journey as a python programmer.

If you need homework help python or looking for someone who can python help then feel free to drop us a message.

Like this article? Follow us on Facebook and LinkedIn.