The Basics of the Python Enumerate() Function

Athena Ozanich
Athena Ozanich



Counting, who needs it?

Woman learning about the Python enumerate function and how to use it.

Well, we all do, and it serves a valuable purpose in programming, too. Programming exists only because of counting and all the maths that can be done with it.

However, programming is not always as straightforward as math and counting are, with that in mind, Python gives us tools to simplify our experience.

In this post, we’ll discuss one of the enumerate functions, which helps us count items and objects within our code. Without any further ado, let’s jump right in.

Download Now: An Introduction to Python [Free Guide]

What does enumerate do in Python?

The enumerate function in Python converts a data collection object into an enumerate object. Enumerate returns an object that contains a counter as a key for each value within an object, making items within the collection easier to access.

Looping through objects is useful but we often need the means to track loops, and the items accessed within that iteration of the loop. Enumerate helps with this need by assigning a counter to each item in the object, allowing us to track the accessed items.

This also makes it easier to manipulate our data collections where such a thing is possible. Not all data collection objects in Python are mutable, sets are a great example of this.

How does enumerate work in Python?

Enumerate functions much like a for loop, it loops over a collection of data once for each item in it. The primary difference is that enumerate also automatically modifies the data it is fed, essentially turning each item into a key-value pair. As the function iterates over the object, each item is paired with a number that corresponds to the number of times the loop has run including the current loop.

The enumerate function accepts two parameters: the required iterable object, and the optional starting number. The starting number parameter accepts an integer and designates what number the function should start counting at. Given that it is optional, the default starting number is always zero, much like the indexing of arrays.

Let’s look at some examples of this, and see how the input is changed by examining the output.

How to use enumerate in Python?

There are four data types in python for storing collections of information, but for this example, we will only go over two. The dictionary and list data types are ordered, and therefore, in most situations — barring complex programming like machine learning — would not need to be run through the enumerator function. On the other hand, sets and tuples are unordered and, therefore, more likely to be enumerated.



Python Enumerate Example

The Python enumerate function offers a more simplistic way to access and count items in a data collection. There are four main data collection types in Python, we will look at examples of the enumerate function with the set and tuple. In the next section, we’ll look at these two contrasting but valuable examples using the enumerate function.

Let’s quickly look at the two data types we will use and what sets them apart from each other.

  • Tuple: Ordered and unchangeable. Allows duplicate members.
  • Set: Unordered, unchangeable (items can be added or removed but not changed), and unindexed. No duplicate members.

Enumerate Python Sets

Python sets are unordered collections of information, the items within them are immutable, and therefore cannot be changed after they are added. The unordered nature of sets means that the order in which the items within are accessed is inconsistent and that they cannot be targeted by an index value as they do not have one.

The enumerate function associates a counter as a key to each item in the set. This can help create structure in an unordered collection. By enumerating on the set we have more control over how we can interact with it in a reliable fashion. This is useful with sets as items within do not have a designated index location.

/*creates a set using curly brackets*/
snekSet = {"cobra","viper","snek"}
/*prints the third object in the tuple*/

The code above would throw an error indicating that a set is not subscriptable, this is due to targeting an index, which is incompatible with sets. However, if we enumerate the set we can then use the counter as an index to find our item.

snekTuple = ("cobra","viper","snek")
for i in enumerate(snekTuple):

The above code would print to the console the following result, though the order the items are returned in may vary.

(0, ‘cobra’)
(1, ‘snek’)
(2, ‘viper’)

It’s important to note that this does not alter the value of snekSet, printing it to the console will give us the same set we declared and very likely in a different order.

{"viper", "cobra", "snek"}

In order to preserve the effect of the enumerate function on a set, you will need to convert the results to a different data type. Let’s look at an example of how we can do that using the list constructor function.

snekSet = {"cobra","viper","snek"}
snekSetEnum = enumerate(snekSet)
snekList = list(snekSetEnum)

First, we create the set, then we run the enumerate function providing our set and save that to a new variable. Finally, the result of the enumeration is then provided to the list constructor and saved as a new list object. The data inside of this new setlist object would look like a list of key/value pairs.

[(0, ‘cobra’), (1, ‘snek’), (2, ‘viper’)]

The issue here is that it produces a convoluted data structure and because sets are unpredictable, they should be used carefully. Let's look at a contrasting use case for the enumerate function, tuples.

Enumerate Python Tuples

The enumerate function can also be used on tuples to get key/value pairs; this comes with much more reliability regarding the order in which items will be returned. The reason for this is because tuples are ordered which means items within it are in the position at which they were added. So, the third item in a tuple — unlike a set — can be targeted using the bracket notation with the index of 2.

/*creates a tuple using parentheses*/
snekTuple = ("cobra","viper","snek")
/*prints the third object in the tuple*/

Enumerating Python tuples is more straightforward than enumerating sets. Enumerating over tuples in Python has far more predictable and consistent results, let’s look at an example of how we would go about doing this.

snekTuple = ("cobra","viper","snek")
for i in enumerate(snekTuple):

For each iteration of the loop, the result will be printed to the console showing the enumerated keys and values for the snekTuple we created.

(0, ‘cobra’)
(1, ‘viper’)
(2, ‘snek’)

It is important to note that this example is a little redundant as tuples are ordered and can be targeted using indexes. That isn’t to say that there isn’t a viable reason or use for this, a great example is enumerating over a dictionary of sets. The sets within the dictionary could be enumerated over to better understand its contents.

Moving Forward With the Python Enumerate Function

There are a lot of useful tricks that can be applied to your programming with the enumerate function and the complexity of your programming will impact how often you’ll need features like the enumerate function. It will also affect how complex the use of such features will be and the enumerate function can be used to perform powerful data restructuring for a variety of needs. Best of luck, and be sure to utilize resources like Stack Overflow and the Python documentation page as needed.


Topics: What Is Python?

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

A guide for marketers, developers, and data analysts.