Introduction to enumerate

Enumerate banner

Are you a developer coming from Java, C , or C++ background..? and had difficulty writing “for loops” in Python? Kindly read as this could save you from tons of bad quality code and to make your code look more pythonic.

Python has a built-in function enumerate() which take iterable as a input and returns an object of enumerate class . For example in below code snippet, we are passing a list as a iterator…

>>> brands = ["Adidas", "Puma", "Reebok", "Nike"]
>>> enumerate(brands)
<enumerate object at 0x024C56s70>

In the above code snippet, we can see that an object of type enumerate class has been returned. Now you will ask..

That’s fine, but How can I use it ?


Enumerate basics

In simple words, Enumerate allows us to loop over an iterable and have an automatic counter. Here is an example:

>>> brands = ["Adidas", "Puma", "Reebok", "Nike"]
>>> for counter, value in enumerate(brands):
        print(counter, value)
"""
Output:
0 Adidas
1 Puma
2 Reebok
3 Nike
"""

As in the above snippet, we can see that enumerate give us a automatic counter starting from 0. I have seen developers coming from different language background such as C++ or Java trying it hard on code to achieve the same through below code snippets..

# Not Pythonic
>>> brands = ["Adidas", "Puma", "Reebok", "Nike"]
>>> for i in range(len(brands)):
        print(i, brands[i])

Don’t do something like that. In fact you should avoid making the code look more complex following “Zen of Python” that says

Simple is better that complex

Enumerate detailed

Let’s check the syntax of enumerate function first and use the another optional parameter available in the function i.e start.

Syntax

enumerate(sequence, start=0)
sequence
Required. Must be a sequence, an iterator, or some other object which supports iteration.
start
Optional. Index at which enumeration starts
Returns : A tuple with the current value of count with the current item from the iterable.

“start” is an optional parameter through which we can tell the enumerate function from which index to start the loop. By default enumerate starts with index 0, we can change this with “start” parameter. Many a times we come across such situation when we want the loop to start from index 1 to correctly count the total no of items. For example. while counting total no of characters in a string or total no of value in a list etc….

Usage of “start” parameters

Now we will see some examples of “start” parameter. For the same above example if we just pass start as 1 then our output will change as follows…

brands = ["Adidas", "Puma", "Reebok", "Nike"]
for counter, value in enumerate(brands, start=1):
    print(counter, value)
"""
Output:
1 Adidas
2 Puma
3 Reebok
4 Nike
"""

We can clearly see that the output now starts from index 1 and apple is at index 1. Similarly we can change that start index to any number and it will start the count from that given number,

Enumerate usage examples

On Tuples

places = ("Maldives", "Bali", "Switzerland", "Bangkok", "Dubai")
for enums in enumerate(places):
    print(enums)
"""
Output:
(0, Maldives)
(1, Bali )
(2, Switzerland)
(3, Bangkok)
(4, Dubai)
"""

On Strings

We can also use enumerate on string, which will give us the index of each characters in it.

Loop using single variable

demo_words = "Hello"
for enums in enumerate(demo_words):
    print(enums)
"""
Output:
(0, H)
(1, e)
(2, l)
(3, l)
(4, o)
"""

Loop using two variable

demo_words = "Hello"
for index,enums in enumerate(demo_words):
    print(index, enums)
"""
Output:
0 H
1 e
2 l
3 l
4 o
"""

On dictionary (Never do this. Why ?)

Since dictionary are not supposed to be ordered, meaning there is no particular order in which the element of the dictionary exist so there is no any point in getting their index. Even if you try to do so you will get it in different order every time you will pass the same dictionary to the enumerate function. Also in the below snippet it is clearly visible that it returns a tuple for keys only not the values.

>>> dict_b = {"abc": "Hello", "def":"World" , "ghi" : "First", "jkl" : "Second"}
>>> list(enumerate(dict_b))
>>> [(0, 'jkl'), (1, 'abc'), (2, 'ghi'), (3, 'def')]

So it is not recommended to do be used on Dictionary. However if you want to iterate over the keys and values of a dictionary you can use items() method on a dictionary.

How Enumerate works ?

The enumerate class is implemented as a Python iterator( implements  __next__) . So If you are using enumerate and call next() on enumerte object, you will receive one tuple each time. Element are generated one by one during the next() call, which keeps memory use low by not generating unnecessary full results at once.

>>> brand = [ "Reebok" , "Puma" , "Adidas" ]
>>> en = enumerate(brand)
>>> en
<enumerate object at 0x024C56C0>
>>> en.next()
(0, "Reebok")
>>> en.next()
(1, "Puma")
>>> en.next()
(2, "Adidas")         

Summary

  • Enumerate is a built-in function of Python which returns an enumerate object.
  • Enumerate accepts an iterable as an input.
  • Enumerate has a optional parameter start which is by default set to 0
  • The start parameter can be set to any integer.
  • Enumerate can be used to loop over a list, tuple, and string or over any iterable.
  • next() can be used to get the item from enumerate object one by one.

Leave a Reply

Your email address will not be published. Required fields are marked *