Python simplifies the tasks performed by the programmers through a built-in function known as enumerate(). In this article, we will walk you through how to iterate over different types of python objects like lists, tuple, strings, etc and get back both the index and also the value of each item. We will be covering the below topics in-depth in this article. Hope you will have fun enumerating :)
If you would like to become a Python certified professional, then visit Mindmajix - A Global online training platform: “Python Certification Training” Course. This course will help you to achieve excellence in this domain.
If you are coming from other programming languages (like C), you must be habituated to the idea of iterating over the length of an array by an index and then further making use of this index to get the value at that location. A lot of times when we are working with iterators, we also get a need to keep a count of the number of iterations.
Python gives you the advantage of iterating directly over the items of the list which is most of the time what you need. However, there are also situations when you actually need the index of the item as well.
Python provides us with a built-in function called enumerate that allows you to do just that. The usefulness of this function cannot be summarized in a single line. Python enumerate function facilitates us to loop over something and have an automatic counter. Though it's very helpful, many newcomers and even some advanced programmers are unaware of it.
What Python Enumerate() method does is that it adds a counter to an iterable and this is returned in a form of enumerating object. This enumerate object can now be used directly in either for loops or can also be converted into a list of tuples with the help of the list() method.
Related Article: Python Tutorial
Benefit of Using Enumerate
You might ask why not use list.index which also returns the index of the list. The problem with list.index is that it has a complexity of O(n) which means you'll be traversing the list more than a couple of times(also considering the for loop itself), and it then returns the starting index of a given item, which means you'll get incorrect results for lists with duplicate items.
This problem is solved by Python enumerate by simply generating the indices and the items on the fly; One cannot get more performance than what the built-in enumerate provides.
Also, one should remember that enumerate is evaluated lazily; a huge plus for large lists. In contrast, you don't want to call the index method of a large list, even if there were no duplicates in the list and the results were correct, you'll still be doing unnecessary traversals across the list.
The syntax of enumerate() is in the following format:
enumerate(iterable, start=0)
The enumerate() method inputs two parameters:
iterable - a sequence, an iterator, or objects that helps in the iteration
start (optional) - In enumerate(), counting starts from this number. If start has been omitted, 0 is taken as start.
Return Value from enumerate():
The enumerate() method adds a counter to an iterable and then returns it. The object which has been returned is an enumerate object.
Let us see a basic python enumerate example and see how it works:
grocery = ['bread', 'milk', 'butter']
enumerateGrocery = enumerate(grocery)
print(type(enumerateGrocery))
# converting to list
print(list(enumerateGrocery))
# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))
After the program has been run, the output will be:
[(0, 'bread'), (1, 'milk'), (2, 'butter')]
[(10, 'bread'), (11, 'milk'), (12, 'butter')]
Let us take an example which demonstrates looping over an enumerate object
grocery = ['bread', 'milk', 'butter']
for item in enumerate(grocery):
print(item)
print('n')
for count, item in enumerate(grocery):
print(count, item)
print('n')
# changing default start value
for count, item in enumerate(grocery, 100):
print(count, item)
After the program has been run, the output will be:
(0, 'bread')
(1, 'milk')
(2, 'butter')
0 bread
1 milk
2 butter
100 bread
101 milk
102 butter
As mentioned earlier, we can convert enumerate objects to list and tuple using list() and tuple() method respectively. Let us take a detailed look at how to do this.
Enumerate a List:
Let us check how we can enumerate a list.
for counter, value in enumerate(some_list):
print(counter, value)
my_list = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(my_list, 1):
print(c, value)
The Output would then be: apple banana grapes pear
Before we move on to enumerating in tuples, it is good to know that you can also create tuples containing the index and list item using a list. Here is an example:
my_list = ['apple', 'banana', 'grapes', 'pear']
counter_list = list(enumerate(my_list, 1))
print(counter_list)
The output would be
[(1, 'apple'), (2, 'banana'), (3, 'grapes'), (4, 'pear')]
Enumerate a Tuple:
To iterate through a tuple object, we can use multiple ways.
The for statement in Python can be used since it has a variant which traverses through a tuple till it is exhausted. It can be considered as equivalent to for each statement in Java.
Its syntax is:
for var in tuple:
stmt1
stmt2
The following script will be printing all items in the list.
T = (10,20,30,40,50)
for var in T:
print (T.index(var),var)
The generated output is
10
20
30
40
50
Another approach would be to iterate over range upto the length of tuple, and then use it as index of item in tuple.
for var in range(len(T)):
print (var,T[var])
One can also get the enumerate object from the tuple and then iterate through it. The following code too gives similar output.
for var in enumerate(T):
print (var)
Enumerate a List of Tuples (The Neat Way)
So far you've looked at what enumerate does in Python and also how to enumerate in a list and also a tuple.
Suppose we have some code like this:
letters = [('a', 'A'), ('b', 'B')]
i = 0
for (lowercase, uppercase) in letters:
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
i += 1
We know that we can rewrite the code using the enumerate() function as this
for i, l in enumerate(['a', 'b', 'c']):
print "%d: %s" % (i, l)
The question here is how will you use enumerate when the list in question is made of tuples?
After some initial thought, you might come up with this:
letters = [('a', 'A'), ('b', 'B')]
for i, tuple in enumerate(letters):
(lowercase, uppercase) = tuple
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
But let us show you a better way to do this. This can also be called the neat way.
letters = [('a', 'A'), ('b', 'B')]
for i, (lowercase, uppercase) in enumerate(letters):
print "Letter #%d is %s/%s" % (i, lowercase, uppercase)
This neater way to achieve is through the concept of tuple unpacking in python. In tuple packing, we place the values into a new tuple and in tuple unpacking we extract those values back into the variables.
Enumerate a String;
Any guesses as to what happens when you use the enumerate function on a string object? An item in a string is considered as a single character. So if you enumerate over a string, you will getting the index and value of each character in the string.
Let’s take an easy example:
str = "Python"
for idx, ch in enumerate(str):
print("index is %d and character is %s"
% (idx, ch))
And the output generated will be:
index is 0 and character is P
index is 1 and character is y
index is 2 and character is t
index is 3 and character is h
index is 4 and character is o
index is 5 and character is n
Enumerate with a Different Starting Index:
As we all know, indices in python start at 0. This tells us that when we use the enumerate function, the index which will be returned for the first item will be 0.But in some cases, you might require the loop counter to be started at a different number.
Related Article: Python Enum
This is allowed by the enumerate() function. This is done through an optional start parameter.
For example, let’s say we want to enumerate over a list whose starting index is at 1.
The code will look similar to this:
L = ['apples', 'bananas', 'oranges']
for idx, s in enumerate(L, start = 1):
print("index is %d and value is %s"
% (idx, s))
The above code will generate this output.
index is 1 and value is apples
index is 2 and value is bananas
index is 3 and value is oranges
Needless to say, one can also start the index with a negative number.
Do you think it makes sense to use the enumerate function for dictionaries and sets?
Absolutely no way!
If you think about it, the only reason you would make use of enumerate is when you actually care about the index of the item. Dictionaries and Sets are not considered to be sequences.
Their items do not have an index, and by their definition, then don't require one.
If you would like to iterate over the keys and values of a dictionary instead (a very common operation), then you achieve that that using the following code:
d = {'a': 1, 'b': 2, 'c': 3}
for k, v in d.items():
# k is now the key
# v is the value
print(k, v)
And if you want to iterate over a set, a regular for loop will suffice.
s = {'a', 'b', 'c'}
for v in s:
print(v)
Advanced: Enumerate Deep Dive
In Python, a python object of type enumerate is returned by the enumerate function
>>> type(enumerate([1, 2, 3]))
The following code shows how the enumerate object is implemented.
/*[clinic input]
class enumerate "enumobject *" "&PyEnum_Type"
class reversed "reversedobject *" "&PyReversed_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d2dfdf1a88c88975]*/
typedef struct {
PyObject_HEAD
Py_ssize_t en_index; /* current index of enumeration */
PyObject* en_sit; /* secondary iterator of enumeration */
PyObject* en_result; /* result tuple */
PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */
} enumobject;
If you observe, the enumerate object stores an index en_index, an iterator en_sit, and a result tuple en_result. en_sit is actually the input parameter which we passed to the enumerate function. This input parameter must be an iterable object.
At a given index, the result is a tuple of two elements in which the first element is the index and the second one is the item in en_sit with that index. Since enumerate objects themselves are iterables with each item being the mentioned result tuple.
>>> list(enumerate(['a', 'b', 'c']))
[(0, 'a'), (1, 'b'), (2, 'c')]
This is the reason why when we iterate over the enumerate object with a for loop like this:
>>> for idx, val in enumerate(['a', 'b']):
... print(idx, val)
...
0 a
1 b
We are successfully unpacking these tuples to an index and a value. But you can't be prevented from doing this too(but don’t do it :))
>>> for i in enumerate(['a', 'b']):
... print(i[0], i[1])
...
0 a
1 b
Before we conclude, let’s look at the key takeaways which we want you to remember.
The enumerate Function in Python – Key Takeaways:
To use enumerate to its fullest potential, we recommend you to study up on Python’s iterators and data structure unpacking features. Hope you have got a strong idea on what enumerate in Python is and how it works.
If you are interested to learn Python and to become an Python Expert? Then check out our Python Certification Training Course at your near Cities.
Python Course Chennai, Python Course Bangalore, Python Course Dallas, Python Course Newyork
These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Python and help you to achieve your dream job.
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
Python Training | Nov 19 to Dec 04 | View Details |
Python Training | Nov 23 to Dec 08 | View Details |
Python Training | Nov 26 to Dec 11 | View Details |
Python Training | Nov 30 to Dec 15 | View Details |
Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex, etc. Connect with him on LinkedIn and Twitter.