What does enumerate () do in python?

Counting, who needs it?

What does enumerate () do in python?

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.

What does enumerate () do in python?

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*/
print(snekSet[2])

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):
print(i)

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.

 
print(snekSet)
/*output*/
{"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*/
print(snekTuple[2])

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):
print(I)

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.

What does enumerate () do in python?

What is the use of enumerate () in Python?

enumerate() allows us to iterate through a sequence but it keeps track of both the index and the element. The enumerate() function takes in an iterable as an argument, such as a list, string, tuple, or dictionary.

What is enumerate in pandas?

The enumerate() function is a built-in function that returns an enumerate object. This lets you get the index of an element while iterating over a list. In other programming languages (C), you often use a for loop to get the index, where you use the length of the array and then get the index using that.

What is enumerate in for loop?

Python's enumerate() lets you write Pythonic for loops when you need a count and the value from an iterable. The big advantage of enumerate() is that it returns a tuple with the counter and value, so you don't have to increment the counter yourself.

What is enumerator in Python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over. An enum has the following characteristics.