By the end of this tutorial, you will be able to use enumerate with lists, tuples, loops, dictionaries, and in reverse order.
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.
Term | Definition |
---|---|
Syntax | In programming, syntax is the set of rules that defines the structure of a language. |
print() is a function that converts a specified object into text and sends it to the screen or other standard output device. | |
Function | A function is a block of code that will only run when it is called upon. |
For loop | An iterating function used to execute statements repeatedly. |
Iterate | In programming, iteration is the repetition of a code or a process until a specific condition is met. |
Iterables | Iterables are objects in Python that you can iterate over. |
Dictionary | In 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. |
Key | Keys 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. |
Value | A 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. |
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:
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:
You can use enumerate with any iterable object in Python. Examples of iterable objects include lists, strings, tuples, and dictionaries.
By default, the syntax of Python enumerate is as follows:
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.
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.
Here’s how the enumerate function works with a list as the iterable and a start value of 0 (the default):
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 writing a program that returns the following output:
1 2 3 4
programs = ['python','c','react','javascript','bash'] for i, program in enumerate(programs,1): print(i, program)
Tip
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:
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:
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 using enumerate to add a counter to the keys of this dictionary:
1
pokemon = {'Pikachu': 'Electric', 'Bulbasaur': 'Grass/Poison', 'Squirtle':'Water', 'Charmander':'Fire'}
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:
1 2
for i, (creature, pokemon_type) in enumerate(pokemon.items()): print(i,creature,pokemon_type)
To enumerate a tuple in Python, you’ll approach it the same way you would enumerate a list:
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:
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:
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:
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 rewriting this for loop with enumerate
:
1 2 3 4
pokemon = ['Pikachu', 'Bulbasaur', 'Squirtle', 'Charmander'] for i in range(len(pokemon)): current_pokemon = pokemon[i] print(i, current_pokemon)
1 2
for i, current_pokemon in enumerate(pokemon): print(i, current_pokemon)
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:
Try using enumerate on the following string to return an object that begins with 5:
1
string = "This is a test string."
1 2 3
string = "This is a test string." for index, char in enumerate(string, start=5): print(index, char)
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:
Can’t I just loop over the list in reverse order?
Can you use enumerate in reverse order to put the list languages
in order from 5 to 1?
1
languages = ['Python', 'Java', 'C++', 'JavaScript', 'C#']
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)
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.
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.