How to Enumerate in Python: Step by Step

Written by Coursera • Updated on

By the end of this tutorial, you will be able to use enumerate with lists, tuples, loops, dictionaries, and in reverse order.

[Featured image] A programmer in a blue shirt enumerates a list in Python on his desktop computer.

Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE) of your choice (or terminal), and a stable internet connection

Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts

Enumerate is a built-in Python function. It enables you to keep track of iterations, write more efficient loops, and access the index and values of an iterable object.

Glossary

TermDefinition
SyntaxIn programming, syntax is the set of rules that defines the structure of a language.
Printprint() is a function that converts a specified object into text and sends it to the screen or other standard output device.
FunctionA function is a block of code that will only run when it is called upon.
For loopAn iterating function used to execute statements repeatedly.
IterateIn programming, iteration is the repetition of a code or a process until a specific condition is met.
IterablesIterables are objects in Python that you can iterate over.
DictionaryIn Python, dictionaries are used to store and retrieve data in key:value pairs. Dictionaries are ordered and mutable (or, changeable) collections. Dictionaries are also referred to as associative arrays.
KeyKeys are like indexes for dictionary values. They can be any data type, but they must be unique and immutable so each key accesses only one value.
ValueA value is one of the most basic elements of any program. Values can represent letters, numbers, or strings of characters.
items()A method of retrieving the key and its corresponding value simultaneously when looping through a dictionary.
list()list() is a mutable sequence type. When used as a function, it takes an iterable and creates a list object.
reversed()reversed() is a built-in Python function that returns a reverse iterator.
enumerate()enumerate is a built-in function. It adds a counter to an iterable (like a sequence) and returns it as an enumerate object.

What is enumerate in Python?

Python enumerate assigns a count to each item within an iterable and returns it as an enumerate object. This function enables you to loop over an iterable while accessing the index of items within it. For example, suppose you want to assign a count to each item in the following sequence:

PYTHON
1
pokemon = ['Pikachu', 'Bulbasaur', 'Squirtle', 'Charmander']

In that case, you could feed this sequence to the function enumerate. The output will include your sequence with a counter, like this:

Screenshot 2023-02-01 at 3.37.37 PM

You can use enumerate with any iterable object in Python. Examples of iterable objects include lists, strings, tuples, and dictionaries.

Enumerate syntax

By default, the syntax of Python enumerate is as follows:

PYTHON
1
enumerate(iterable, start=0)

You can adjust the enumerate function to fit your needs by changing its parameters. Enumerate has two parameters:

1. Iterable: The iterable is the sequence, list, or objects you select to enumerate. This is a required parameter.

2. Start: The start value lets the enumerate function know which number to start counting from. This is an optional parameter. If you omit it, the start will be 0.

How to use enumerate in Python

Passing an iterable to enumerate() returns an enumerated object that you can iterate through with a for loop or convert to alist of tuples using the list() method. This function may be helpful anytime you want to keep count of or access iterable items. In the following sections, we’ll examine how the enumerate function works with lists, dictionaries, tuples, strings, for loops, and in reverse.

How to enumerate a list in Python

Here’s how the enumerate function works with a list as the iterable and a start value of 0 (the default):Screenshot 2023-02-01 at 3.47.10 PM

enumerate() takes a list called "fruits" as an argument and returns an enumerate object, which contains pairs of indices and corresponding items from the list. The for loop unpacks each pair into i and fruit variables, where i is the index and fruit is the corresponding item.

Try it yourself

Try writing a program that returns the following output: Screenshot 2023-02-01 at 3.55.17 PM

PYTHON
1
2
3
4
programs = ['python','c','react','javascript','bash']

for i, program in enumerate(programs,1):
  print(i, program)

Tip

Enumerate objects are immutable, which means you cannot change, remove, or add values to them.

How to enumerate a dictionary in Python

There are two ways to enumerate a dictionary in Python. The first method will only assign a counter to the keys of a dictionary, not the values: Screenshot 2023-02-01 at 4.02.07 PM

This method returns a list of the keys in the dictionary, which can then be passed to enumerate() just like in our example with the list. The rest of the code works the same way.

The second technique uses the items() function to assign a counter or a count variable to both the keys and the values in a dictionary:Screenshot 2023-02-01 at 4.05.43 PM

The .items() method returns a list of key-value pairs from the dictionary, which can then be passed to enumerate(). The for loop unpacks each pair into fruit and color variables, where fruit is the key and color is the corresponding value.

Try it yourself

Try using enumerate to add a counter to the keys of this dictionary:

PYTHON
1
pokemon = {'Pikachu': 'Electric', 'Bulbasaur': 'Grass/Poison', 'Squirtle':'Water', 'Charmander':'Fire'}

PYTHON
1
2
for i, creature in enumerate(pokemon.keys()):
  print(i,creature)

Now, try adding items() to add a counter to the values in the same dictionary:

PYTHON
1
2
for i, (creature, pokemon_type) in enumerate(pokemon.items()):
  print(i,creature,pokemon_type)

How to enumerate a tuple in Python

To enumerate a tuple in Python, you’ll approach it the same way you would enumerate a list: Screenshot 2023-02-01 at 4.51.28 PM

The code works in the same way as the previous examples with a list, except that a tuple is used instead. enumerate takes a tuple as an argument and returns an enumerate object, which contains pairs of indices and corresponding items from the tuple.

However, if you need to use enumerate to iterate through a list of tuples, you’ll write it a little differently: Screenshot 2023-02-02 at 9.06.41 AM

How to use enumerate a Python for loop

The enumerate function can help you write cleaner, more efficient for loops in Python. Without it, you would need to loop over the range of the iterable and increment the counter yourself. Although both methods achieve the same effect, enumerate is more straightforward and readable. Here is a side-by-side comparison:

Without enumerate: Screenshot 2023-02-02 at 9.11.46 AM

Here, the range function generates a sequence of indices from 0 to len(fruits) - 1 (2 in this case). The for loop iterates over these indices and uses each index i to obtain the corresponding item fruit from the list fruits.

With enumerate: Screenshot 2023-02-02 at 9.14.46 AM

This code is the same as the previous example, but it uses the enumerate function instead of the range function. enumerate takes the list fruits as an argument and returns an enumerate object, which contains pairs of indices and corresponding items from the list.

Try it yourself

Try rewriting this for loop with enumerate:

PYTHON
1
2
3
4
pokemon = ['Pikachu', 'Bulbasaur', 'Squirtle', 'Charmander']
for i in range(len(pokemon)):
    current_pokemon = pokemon[i]
    print(i, current_pokemon)

PYTHON
1
2
for i, current_pokemon in enumerate(pokemon):
  print(i, current_pokemon)

How to enumerate a string in Python

Since strings are iterable in Python, they can be passed to the enumerate function as well. Enumerating a string will return its index and value pairs. Here’s an example using enumerate on a string starting from 1:

Screenshot 2023-02-02 at 9.28.09 AM

Try it yourself

Try using enumerate on the following string to return an object that begins with 5:

PYTHON
1
string = "This is a test string."

PYTHON
1
2
3
string = "This is a test string."
for index, char in enumerate(string, start=5):
  print(index, char)

How to enumerate in reverse order in Python

You can’t reverse the type of object that the enumerate function returns. However, you can reverse the order by converting the enumerate object into a list or tuple first. You’ll accomplish this by using Python’s list() or tuple() and reversed() functions. Here’s an example: Screenshot 2023-02-02 at 9.46.56 AM

Can’t I just loop over the list in reverse order?

If you use this method, the index will be returned incorrectly (starting from 0).

Try it yourself

Can you use enumerate in reverse order to put the list languages in order from 5 to 1?

PYTHON
1
languages = ['Python', 'Java', 'C++', 'JavaScript', 'C#']

PYTHON
1
2
3
4
5
enumerated_languages = tuple(enumerate(languages, 1))
reversed_languages = reversed(enumerated_languages)

for index, value in reversed_languages:
  print(index, value)

Key takeaways

  • The enumerate function adds a counter to an iterable and returns it as an enumerate object.
  • Enumerate has two parameters: the iterable and the start value.
  • You can use enumerate with any iterable in Python.
  • You can reverse the order of enumeration by converting the enumerate object to a list or tuple and reversing it.
  • Enumerate lets you access both the index and the value simultaneously.

Resources

Keep improving your Python programming skills with Coursera.

Keep practicing your skills with a Guided Project like Concepts in Python: Loops, Functions, and Returns. Or, take the next step in mastering the Python language and enhance your resume by earning a certificate from the University of Michigan in Python 3 Programming.


Written by Coursera • Updated on

This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.

Learn without limits