This tutorial will teach you how to use the enumerate() function in Python.

The enumerate() function in Python provides a concise syntax to access the items in an iterable along with their indices.

We’ll start by reviewing how to access items and indices using simple looping and then proceed to learn the syntax of Python’s enumerate() function. We’ll also code examples along the way.

Let’s begin.

How to Iterate Using for Loop in Python

Any Python object that you can iterate over and access the individual items—one at a time is called an iterable. Therefore, Python lists, tuples, dictionaries, and strings are all iterables.

python-enumerate-img

Let’s take an example of a shopping list defined in the code cell below.

shopping_list = ["fruits","cookies","cereals","protein bars","post-it notes"]

In Python, you can use the for loop to loop through any iterable. The syntax to do this is as follows:

for item in <iterable>:
    # do something on item

# item: looping variable
# <iterable>: any Python iterable: list, tuple, dictionary, string, and so on.

Now, using this syntax, let’s loop through shopping_list and access the individual items.

for item in shopping_list:
  print(item)

# Output
fruits
cookies
cereals
protein bars
post-it notes

This construct helps you access the items directly. However, you may sometimes need to access the index of the items, in addition to the items themselves.

You can use an index variable, which you can increment inside the loop body, as shown below:

index = 0
for item in shopping_list:
  print(f"index:{index}, {item}")
  index += 1

# Output
index:0, fruits
index:1, cookies
index:2, cereals
index:3, protein bars
index:4, post-it notes

But this is not the most efficient method. If you don’t remember to increment the index, your code will not work as expected.

index = 0
for item in shopping_list:
  print(f"index:{index}, {item}")
  # no update of index inside loop body
  # index is never updated and is always 0

# Output
index:0, fruits
index:0, cookies
index:0, cereals
index:0, protein bars
index:0, post-it notes

Another common pattern of using the for loop is in conjunction with the range() function. We’ll learn about that in the next section.

How to Use range() Function to Access Index

Python’s built-in len() function returns the length of any Python object. So you can call the len() function with shopping_list the argument to get the length of the shopping_list (which is 5, in this case).

len(shopping_list)
# Output: 5

The range() function returns a range object which you can then use in looping. When you loop through range(stop), you get the indices 0, 1, 2,…, stop-1.

By setting stop = len(list), you can get the list of valid indices. So by using the range() function, you can access the index as well as the corresponding item, as shown below.

for index in range(len(shopping_list)):
  print(f"index:{index}, item: {shopping_list[index]}")

# Output
index:0, item: fruits
index:1, item: cookies
index:2, item: cereals
index:3, item: protein bars
index:4, item: post-it notes

However, this is not the recommended Pythonic way to access both indices and items simultaneously.

Syntax of Python enumerate() Function

Python’s enumerate() function lets you access the items along with their indices using the following general syntax:

enumerate(<iterable>, start = 0)

In the above syntax:

  • <iterable> is a required parameter, and it can be any Python iterable, such as a list or tuple.
  • start is an optional parameter that controls the index at which the counting starts. If you don’t specify the value of start, it defaults to zero.

You can now call the enumerate() function with shopping_list and it returns an enumerate object, as shown in the code cell below.

enumerate(shopping_list)
<enumerate at 0x7f91b4240410>

You cannot loop through the enumerate object. So let’s convert the enumerate object into a Python list.

list(enumerate(shopping_list))

# Output
[(0, 'fruits'),
 (1, 'cookies'),
 (2, 'cereals'),
 (3, 'protein bars'),
 (4, 'post-it notes')]

Another method to access the items of the enumerate object is to call the next() function with the enumerate object as the argument. In Python, the next() function returns the next item from an iterator.

Internally, the next() function works by calling the __next__ method on the iterator object to retrieve the successive items.

Let’s assign the enumerate object to the variable shopping_list_enum.

shopping_list_enum = enumerate(shopping_list)

When you first call next() with shopping_list_enum, you’ll get index zero and the item at index 0: the tuple (0, 'fruits').

When you continue to make further calls to the next() function, you’ll get the successive items along with their indices, as described below.

next(shopping_list_enum)
# (0, 'fruits')
next(shopping_list_enum)
# (1, 'cookies')
next(shopping_list_enum)
# (2, 'cereals')
next(shopping_list_enum)
# (3, 'protein bars')
next(shopping_list_enum)
# (4, 'post-it notes')

What happens if you call next() function after you’ve accessed all items and have reached the end of the list? You get a StopIteration Error.

next(shopping_list_enum)
# ---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-16-4220f68f6c7e> in <module>()
----> 1 next(shopping_list_enum)

StopIteration:

The enumerate() function returns the successive indices and items only when needed and are not computed ahead of time. In Python projects where you need to take memory efficiency into account, you can try using the enumerate() function when you need to loop through large iterables.

Python enumerate() Function Examples

Now that we’ve learned the syntax to use the enumerate() function, let us modify the for loop we had earlier.

From the previous section, we know that looping through the enumerate object returns a tuple with the index and the item. We can unpack this tuple into two variables: index and item.

for index, item in enumerate(shopping_list):
  print(f"index:{index}, item:{item}")

# Output
index:0, item:fruits
index:1, item:cookies
index:2, item:cereals
index:3, item:protein bars
index:4, item:post-it notes

Next, let’s see how to specify a custom start value.

How to enumerate() with Custom Start Value

Python follows zero indexing, so the start value is 0 by default. However, if you need the indices in human-readable form—starting from 1 or any other index of your choice, you can specify a custom start value.

In the shopping_list example, if you’d like to start counting from 1, set start = 1.

for index, item in enumerate(shopping_list,1):
  print(f"index:{index}, item:{item}")

# Output
index:1, item:fruits
index:2, item:cookies
index:3, item:cereals
index:4, item:protein bars
index:5, item:post-it notes

However, when specifying the custom start value, you should be sure to specify it as the second positional argument.

If you mistakenly swap the order of the iterable and the start value, you would run into an error, as explained in the code cell below.

for index, item in enumerate(1,shopping_list):
  print(f"index:{index}, item:{item}")

# Output
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-5dbf7e2749aa> in <module>()
----> 1 for index, item in enumerate(1,shopping_list):
      2   print(f"index:{index}, item:{item}")

TypeError: 'list' object cannot be interpreted as an integer

To avoid such errors, you can specify start as a keyword argument, as shown below.

for index, item in enumerate(shopping_list, start = 1):
  print(f"index:{index}, item:{item}")

# Output
index:1, item:fruits
index:2, item:cookies
index:3, item:cereals
index:4, item:protein bars
index:5, item:post-it notes

So far, you’ve learned how to use the enumerate() function with Python lists. You can also use the enumerate function to loop through Python strings, dictionaries, and tuples.

How to Use enumerate() Function with Python Tuples

Suppose shopping_list is a tuple. In Python, tuples are also collections—similar to Python lists, but they are immutable. Therefore, you cannot modify them, and trying to do so will lead to error.

The following code snippet initializes shopping_list as a tuple.

shopping_list = ("fruits","cookies","cereals","protein bars","post-it notes")
type(shopping_list)
# Tuple

If you try to modify the first item in the tuple, you will get an error as a Python tuple is an immutable collection.

shopping_list[0] = 'vegetables'

# Output
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-ffdafa961600> in <module>()
----> 1 shopping_list[0] = 'vegetables'

TypeError: 'tuple' object does not support item assignment

▶ Now, run the following code snippet to verify that the enumerate() function works as expected with tuples.

shopping_list = ("fruits","cookies","cereals","protein bars","post-it notes")
for index, item in enumerate(shopping_list):
    print(f"index:{index}, item:{item}")

How to Use enumerate() Function with Python Strings

You can also use the Python enumerate() function to loop through strings and access the characters and indices simultaneously.

Here is an example.

py_str = 'Butterfly'
for index, char in enumerate(py_str):
  print(f"index {index}: {char}")

# Output
index 0: B
index 1: u
index 2: t
index 3: t
index 4: e
index 5: r
index 6: f
index 7: l
index 8: y

From the output above, we see that the characters along with their indices (0-8) have been printed out.

Conclusion👩🏽‍💻

Here’s a summary of what you’ve learned.

  • You can use for loops to access the items and maintain a separate counter or index variable.
  • If you’d like, you can use the range() function to get the valid indices and access the items by indexing into the list.
  • As a recommended Pythonic way, you can use Python’s enumerate() function with the syntax: enumerate(iterable). By default, the count or index starts at 0.
  • You can specify the custom start value with the syntax enumerate(iterable, start) to get the index starting at the value start and the corresponding items.
  • You can use the enumerate function when working with tuples, strings, dictionaries, and in general, any Python iterable.

I hope you found this tutorial on enumerate() function helpful. Next, learn how to find the index of an item in Python lists. Keep coding!