what is enumerate 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.
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.
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.
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.
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.
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.
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.
The above code would print to the console the following result, though the order the items are returned in may vary.
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.
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.
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.
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.
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.
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.
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.
Syntax:
Parameters:
Example
Using Enumerate object in loops:
This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or have more information about the topic discussed above.
Enumerate is a built-in function in python that allows you to keep track of the number of iterations (loops) in a loop. This enumerate object contains a count (from the start, which always defaults to 0) and a value obtained from iterating over the iterable object.
In this article you will learn all that you need to get started using enumerate() in your code. Namely, we will explore:
Let's get started.
Let's take an example. Suppose we have a list of student names:
We want to create a list of tuples, where each tuple item contains a student ID number and student name like this:
The student ID is the index of the student name in the names list. So in the tuple (3, 'Bianca') student Bianca has an ID of 3 since Bianca is at index 3 in the names list. Similarly in (0, 'Wednesday'), student Wednesday has an ID of 0 since she is at index 0 in the names list.
Whenever we come across situations when we want to use a list item as well the index of that list item together, we use enumerate(). enumerate() will automatically keep track of the order in which items are accessed, which gives us the index value without the need to maintain a separate index variable.
Here's how we can create the student ID and name list of tuples using enumerate():
Let's take a closer look at the syntax for this function.
First, let's look at enumerate(iterable, start=0).
Enumerate needs only two input arguments:
enumerate() will return an enumerate object which essentially holds a list of tuples. Each tuple contains an item from the iterable and the item's count value.
For more details on the input arguments and variations, you can refer to the documentation here.
We can call enumerate like this:
The output
We get a list of tuples. Each tuple is of the form (count, element of names list) with the default start value of zero, so the count starts at zero.
The 1st element of names list and count = 0 forms the 1st tuple. The second element of the names list and count = 1 forms the second tuple. Similarly, the 4th element of the names list and count = 3 forms the last tuple.
There are different ways to invoke enumerate(), such as:
Let's look at each of these with examples.
You'll want to use this option when you have a requirement that the index values must start from some specific value. For example, for this student name list:
We want a list of student IDs and names with the restriction that the IDs must start from 1. In that case, we can invoke enumerate with a start parameter like this:
Now the count value returned by enumerate starts at 1 and not zero like in the previous output. If we have a restriction that student IDs must start from 100, then we can get the desired output by just making start=100:
We can convert the output of enumeration into a list, tuple, or dictionary by calling the corresponding constructor of that type.
To get a list, we use this syntax:
For a tuple, we use this syntax:
Notice how the outputs look almost alike, except the tuples in the first one are enclosed in , signifying it is a list of tuples. In the second one, they're enclosed in ( ) meaning it is a tuple of tuples:
For a dictionary, use the constructor like this:
The default way enumerate treats dictionaries is a little different than how it works with lists or tuples.
Dictionaries are a mapping type with a key value pair, and enumerate() only iterates over the keys and not the values by default.
For example,
Enumerate only considers the keys of the dictionary and returns the count value. This is not useful when we want an index for both the key and the value.
We can enumerate over both keys and values like this:
We may often come across situations when we need to maintain a collection of user-defined objects and iterate over that collection. Any object is an iterable if it has the __iter__ and __next__ methods defined.
In this section, we'll learn how to create our own iterable and then use enumerate with it.
Let's say we want to keep track of which students are attending a fictional school called Nevermore Academy in which year. We create a Student class to represent each student and a Nevermore class to represent the school.
We want to perform the same task like we did previously: create a list of tuples with student ID and student name. But now, instead of a list, we have to deal with a list of objects stored in an instance variable of an object of type Nevermore.
Here's the definition for the Student class. For each student, we have two instance variables – student name and special power of the student.
Now let's create a few Student objects:
Next, let's define the Nevermore class. It has 3 instance variables to store year, the list of Student objects who are attending Nevermore for that year, and an index variable i. This variable will be used for iteration in the __next__ method.
The constructor looks like this:
Let's add an instance method using which the students instance variable will be populated:
It takes as input a Student object and appends it to the list.
Next, we define the methods we need to make it an iterable:
Enumerate will be accessing the items in the iterable based on what the __next__ method returns.
In __next__ we go over the list using the instance variable i as the index. So long as the index is valid we return the name of the Student object in the students array.
Once we have gone over all students, we raise a StopIteration exception, which is a standard method to signify the end of iteration.
Here's the full class definition:
Let's create a Nevermore object for the year 2022:
And now let's add some students to the 2022 batch:
batch is now our custom object that has instance variables – year, a string, and students, a list of Student objects. We now invoke enumerate like this:
We'll get the output like this, where we have the count in which the student object is accessed, which is our student ID and the student name. We added Rowan first to the list so the count value is 0. We added Enid second so the count value is 1, and so on.
In our applications, we might want to use the output from enumerate for further processing, like getting the student ID and name and then using that value to access another data structure. The most common way to utilize enumerate() is through a for loop.
We can unpack the output of the enumeration within a for loop like this:
enumerate() returns a tuple for each iterable item. The first value in the tuple is the count value which we store in the student_id for loop variable. The second value in the tuple is the list item which we store in the name for loop variable.
We might have a dataframe where, corresponding to each student, we have certain other information like extra curricular activities. We set the index to student_id so we can access any row in the df using the student_id value using df.loc method
Using the student_id and name from enumeration, we can access the dataframe like this:
A for loop in Python uses collection-based iteration. This means that Python assigns the next item from an iterable to the loop variable on every iteration, like in this example:
In this example, values is a list with three strings, "a", "b", and "c". In Python, lists are one type of iterable object. In the for loop, the loop variable is value. On each iteration of the loop, value is set to the next item from values.
Next, you print value onto the screen. The advantage of collection-based iteration is that it helps avoid the off-by-one error that is common in other programming languages.
Now imagine that, in addition to the value itself, you want to print the index of the item in the list to the screen on every iteration. One way to approach this task is to create a variable to store the index and update it on each iteration:
In this example, index is an integer that keeps track of how far into the list you are. On each iteration of the loop, you print index as well as value. The last step in the loop is to update the number stored in index by one. A common bug occurs when you forget to update index on each iteration:
In this example, index stays at 0 on every iteration because there’s no code to update its value at the end of the loop. Particularly for long or complicated loops, this kind of bug is notoriously hard to track down.
Another common way to approach this problem is to use range() combined with len() to create an index automatically. This way, you don’t need to remember to update the index:
In this example, len(values) returns the length of values, which is 3. Then range() creates an iterator running from the default starting value of 0 until it reaches len(values) minus one. In this case, index becomes your loop variable. In the loop, you set value equal to the item in values at the current value of index. Finally, you print index and value.
With this example, one common bug that can occur is when you forget to update value at the beginning of each iteration. This is similar to the previous bug of forgetting to update the index. This is one reason that this loop isn’t considered Pythonic.
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. That is not Pythonic, instead you should use enumerate().
In Python you can iterate over the list while getting the index and value immediately.
Related course: Complete Python Programming Course & Exercises
The basic syntax is is enumerate(sequence, start=0)
The output object includes a counter like so: (0, thing), (1, thing), (2, thing),
As input it takes a sequence like a list, tuple or iterator. The start parameter is optional.If the start parameter is set to one, counting will start from one instead of zero
Create a sequence and feed it to the enumerate function. This can be any type of sequence, in this example we use a list. Then we output the object.
Try the program below:123456# create a sequencebrowsers = # create an enumeratable and convert to listx = list(enumerate(browsers))print(x)
You should see this output:
The returned object can be treated like an iterator: the next method call will work:
Let’s see how you can enumerate a Python list. You can open the Python shell to try it out.
You can iterate over a Python list by using enumerate(). Lets see that in a simple example.
It outputs both the index (i) and the value (j).
That was easy!
Lets see how you can enumerate a tuple.
You can enumerate a Python tuple, which isn’t very different from iterating over a list.The code below shows you how to iterate over a tuple:
As expected, it outputs both the index and the value, where the value now is the whole tuple.
If you want instead a more clean output, you can use tuple unpacking.
With tuple unpacking (and f-strings formatting), you get a clean output like this:
Can you iterate over a string object?
Yes you can, every item in the string is a character. This gives you the character index and the character value, for every character in the string.
If you have a string you can iterate over it with enumerate(string).The example below shows you how to do that:
The code output above shows both the index and the value for every element of the string.
The enumerate() function has another parameter, the starting index. By default indicides start at zero.
You can change that, lets say you want to start at the second parameter.
The code will look like this:
It makes no sense to enumerate on a dictionary, because a dictionary is not a sequence.A dictionary does not have an index, it’s not always in the same order.
If you want to iterate over a dictionary, you don’t need enumerate but the traditional:
If you are a beginner, then I highly recommend this book.
Try the exercises below