- Python enumerate: Python Looping with Index Counters
- Understanding the Python enumerate() Function with a List
- Making the Case for the Python enumerate() Function
- Using Python enumerate With a Different Start Index
- Using Python enumerate to Iterate over a Dictionary
- Using Python enumerate In Reverse
- Using Python enumerate to Iterate over a Tuple
- Using Python enumerate to Iterate over a String
- Conclusion
- Additional Resources
- Python enumerate() – What is the Enumerate Function in Python?
- What Is the Syntax of the enumerate() Function in Python?
- How to Use the enumerate() Function in Python
- enumerate() Function in Python Example #1
- enumerate() Function in Python Example #2
- How to Loop Through an Enumerate Object in Python
- Summary
Python enumerate: Python Looping with Index Counters
In this tutorial, you’ll learn how to use the Python enumerate function to improve your Python for loops. The Python enumerate() function allows you to loop over an iterable object, such as lists or dictionaries while accessing the item’s index position. The enumerate() function lets you write significantly cleaner Python for-loops.
By the end of this tutorial, you’ll have learned:
- What the Python enumerate() function is
- Why the Python enumerate() function is useful
- How to use the enumerate() function to loop over Python lists, tuples, strings, and dictionaries
- How to start at a different index counter using the Python enumerate() function
- How to use the Python enumerate() function in reverse
Understanding the Python enumerate() Function with a List
The Python enumerate() function is an incredibly versatile function that allows you to access both the index and item of an iterable, while looping over an object. The best way to understand the usefulness of the function is to use it!
Let’s take a look at an example of using the enumerate() function by passing in a list:
# Using the Python enumerate() Function websites = ['datagy', 'google', 'askjeeves'] for item in enumerate(websites): print(item) # Returns: # (0, 'datagy') # (1, 'google') # (2, 'askjeeves')
We can see that the enumerate() function returns a tuple for each item in the item passed into it. The tuple is made up of the index of the item and the item itself.
Because we can unpack these items right away, we can actually improve how we use this code. Let’s see what this looks like:
# Accessing the Index and Value of Our enumerate Object websites = ['datagy', 'google', 'askjeeves'] for idx, website in enumerate(websites): print(f" - ") # Returns: # 0 - datagy # 1 - google # 2 - askjeeves
We can see that we were able to unpack both items in the returned tuple. We can then access both the index and the value itself in our iteration.
In the next section, you’ll learn how to better understand the utility of the function by comparing it to other ways of accomplishing the same thing!
Making the Case for the Python enumerate() Function
Without using the Python enumerate() function we’re able to implement something similar by looping over the range of the length of the iterable object.
Let’s see what this looks like:
# How to Access the Index and Item Without enumerate websites = ['datagy', 'google', 'askjeeves'] for idx in range(len(websites)): print(idx, websites[idx]) # 0 datagy # 1 google # 2 askjeeves
We can see that this approach works. However, it’s not the most readable approach, and it makes it unclear what we’re actually accessing.
Because it’s important to strive for readability in your code, the Python enumerate() function can make your code much cleaner!
Using Python enumerate With a Different Start Index
So far, we’ve looked at the Python enumerate function by simply passing in a list. The enumerate function, however, also has an optional parameter, start= . As the name implies, this parameter defines the start value for the index.
By default the parameter is set to start=0 , meaning that the first index will start at 0. This makes sense, since Python items tend to be 0-indexed. However, in some cases this may not be what you want.
For example, image that you have a list containing directions. In this case, you may want to start at step 1, since step 0 doesn’t make much sense. Let’s see what this looks like:
# Starting at a Different Start Index directions = ['turn right', 'turn left', 'go straight', 'turn right'] for step, direction in enumerate(directions, start=1): print(f'Step : ') # Returns: # Step 1: turn right # Step 2: turn left # Step 3: go straight # Step 4: turn right
We can see that this result is much more readable!
Using Python enumerate to Iterate over a Dictionary
Using the Python enumerate() function on a dictionary works a bit differently than you might expect. What happens is that the function returns an “index” starting at 0 (remember, dictionaries aren’t indexed) and the key of the dictionary.
Let’s see what this looks like:
# Using Python enumerate() on a Dictionary ages = for idx, item in enumerate(ages): print(idx, item) # Returns: # 0 Nik # 1 Kate # 2 John # 3 Mike
This may not be what you’re expecting! What you may instead want to do is be able to loop over the key and value of each key:value pair in the dictionary.
In order to do this, you can simply iterate over the return value from the .items() method:
# Iterating over a Key and Value in a Dictionary ages = for key, value in ages.items(): print(key, value) # Returns: # Nik 33 # Kate 32 # John 31 # Mike 30
This is much more likely what we were expecting to have returned!
Using Python enumerate In Reverse
In this section, you’ll learn how to use the Python enumerate function to iterate over a list in reverse order. The enumerate function technically returns a generator object. These objects can’t be reversed. Because of this, we first need to turn the result into a list and reverse that object.
# Using enumerate In Reverse Order websites = ['datagy', 'google', 'askjeeves'] for idx, website in reversed(list(enumerate(websites))): print(idx, website) # Returns: # 2 askjeeves # 1 google # 0 datagy
At first glance, it may seem intuitive to loop over the list in reverse order. However, this doesn’t return the index in the correct, as it would begin at 0.
Using Python enumerate to Iterate over a Tuple
Using the Python enumerate function to iterate over a tuple works in the same way as using the function on a string. The function will return a tuple containing the index and the item.
Let’s see what this looks like:
# Using enumerate() on a Python tuple websites = ('datagy', 'google', 'askjeeves') for idx, website in enumerate(websites): print(idx, website) # Returns: # 0 datagy # 1 google # 2 askjeeves
Using Python enumerate to Iterate over a String
An interesting thing about Python strings is that they are iterable. Because of this, we can also pass a string into the enumerate() function in order to return the index and value pairs. This works in the same way as passing in lists or tuples.
Let’s look over a string passing in a starting at the value of 1:
# Using the Python enumerate() Function on a String website = 'datagy' for idx, letter in enumerate(website): print(f'Letter is ') # Returns: # Letter 0 is d # Letter 1 is a # Letter 2 is t # Letter 3 is a # Letter 4 is g # Letter 5 is y
Conclusion
In this tutorial, you learned how to use the Python enumerate() function to loop over an object while accessing both the index and the value at the same time. You explored how the function works and why it’s better than other approaches.
Then, you learned how to use the Python enumerate() function with a different start index and in reverse order. Then, you learned how to use the function to iterate over a dictionary, a tuple, and a string.
Additional Resources
To learn more about related topics, check out the tutorials below:
Python enumerate() – What is the Enumerate Function in Python?
Ihechikara Vincent Abba
The enumerate() function in Python takes in a data collection as a parameter and returns an enumerate object.
The enumerate object is returned in a key-value pair format. The key is the corresponding index of each item and the value is the items.
In this article, we’ll see some examples of how to use the enumerate() function in Python.
We’ll talk about the syntax and parameters, how to use enumerate() , and how to loop through an enumerate object.
What Is the Syntax of the enumerate() Function in Python?
Here is the syntax of the enumerate() function and its parameters:
The enumerate() function takes in two parameters: iterable and start .
- iterable is the data collection passed in to be returned as an enumerate object.
- start is the starting index for the enumerate object. The default value is 0 so if you omit this parameter, 0 will be used as the first index.
How to Use the enumerate() Function in Python
In this section, we’ll look at some examples to help us understand the syntax and parameters shown in the last section.
Note that we have to specify the type of data format (like lists, sets, and so on) the enumerate object will be stored in when returned. You’ll understand this better in the examples.
enumerate() Function in Python Example #1
names = ["John", "Jane", "Doe"] enumNames = enumerate(names) print(list(enumNames)) # [(0, 'John'), (1, 'Jane'), (2, 'Doe')]
In the example above, we created a list called names .
We then converted the names variable into an enumerate object: enumerate(names) , and stored it in a variable called enumNames .
We wanted the enumerate object to be stored in a list when returned, so we did this: list(enumNames) .
When printed to the console, this is what the result looked like: [(0, ‘John’), (1, ‘Jane’), (2, ‘Doe’)]
As you can see in the result, they are in key-value pairs. The first index is 0 which is attached to the first item in the names list, the second is 1 and is attached to the second item in the names list, and so on.
In our example, we only used the first parameter.
In the next example, we’ll make use of both parameters so you can understand how the second parameter work.
enumerate() Function in Python Example #2
names = ["John", "Jane", "Doe"] enumNames = enumerate(names, 10) print(list(enumNames)) # [(10, 'John'), (11, 'Jane'), (12, 'Doe')]
In the example above, we’ve added a second parameter to the enumerate() function: enumerate(names, 10) .
The second parameter is 10. This will signify the starting index for the keys (indexes) in the enumerate object.
Here is our result: [(10, ‘John’), (11, ‘Jane’), (12, ‘Doe’)]
From the result, we can see that the first index is 10, the second 11, and so on.
How to Loop Through an Enumerate Object in Python
Here’s a simple example that shows how we can loop through an enumerate object in Python:
names = ["John", "Jane", "Doe"] enumNames = enumerate(names) for item in enumNames: print(item) # (0, 'John') # (1, 'Jane') # (2, 'Doe')
Using a for loop, we iterated through the enumerate object: for item in enumNames:
When printed out, we got the items in the object listed out in their corresponding key-value pair order.
We can also make use of the second parameter like we did in the last section to change the starting value of the keys.
Summary
In this article, we talked about the enumerate() function in Python.
We started by taking a look at the function’s syntax and parameters.
We then saw some examples which helped us understand how to use the enumerate() function and its parameters.
Lastly, we saw how to loop through enumerate objects in Python using the for loop.