Enumerate() in Python

Enumerate() in Python

In this article, we will talk how to use the Python's `enumerate()` function. A lot of times when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task. Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.

enumerate() is a built-in function in Python that allows you to have an automatic counter while looping over iterables. A lot of times when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task.

Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.

Python enumerate() Function

The enumerate() function takes the following form:

enumerate(iterable, start=0)

The function accepts two arguments:

  • iterable - An object that supports iteration.
  • start - The number from which the counter starts. This argument is optional. By default, counter starts from 0.

enumerate() returns an enumerate object on which you can call the __next__() (or next() in Python 2) method to get a tuple containing a count and the current value of the iterable.

Here is an example of how to create a list of tuples using list() and how to loop over an iterable:

directions = ["north", "east", "south", "west"] 
list(enumerate(directions))

for index, value in enumerate(directions): 
    print("{}: {}".format(index, value))
[(0, 'north'), (1, 'east'), (2, 'south'), (3, 'west')]

0: north
1: east
2: south
3: west

If the zero-based indexing doesn't work for you, choose another starting index for the enumeration:

directions = ["north", "east", "south", "west"] 
list(enumerate(directions, 1))
[(1, 'north'), (2, 'east'), (3, 'south'), (4, 'west')]

The enumerate() function works on any iterable object. An iterable is a container that can be iterated over. Putting it in simple words, it means an object that you can loop over with a for loop. Most of the built-in objects in Python like strings, lists, and tuples are iterables.

Write More Pythonic Code with enumerate()

Python's for loop is totally different from the traditional C-style for loop which is available in many programming languages. The for loop in Python is equivalent to other languages’ foreach loop.

A common technique used by new Python developers to get the corresponding index when dealing with iterables is to use either the range(len(...)) pattern or set and increment a counter:

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
for i in range(len(planets)):
    print("Planet {}: {}".format(i, planets[i]))
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
i = 0
for planet in planets:
    print("Planet {}: {}".format(i, planet))
    i += 1

The loops above can be rewritten in more idiomatic way using enumerate():

planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
for index, value in enumerate(planets): 
    print("Planet {}: {}".format(index, value))

All methods will produce the same output:

Planet 0: Mercury
Planet 1: Venus
Planet 2: Earth
Planet 3: Mars
Planet 4: Jupiter
Planet 5: Saturn
Planet 6: Uranus
Planet 7: Neptune

Conclusion

In this article, we have shown you how to use the Python's enumerate() function.

Thank you for reading !

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Learn Python Tutorial from Basic to Advance

Basic programming concept in any language will help but not require to attend this tutorial

Best Way to Learn Python Programming Language | Python Tutorial

Worried that you have no experience in handling Python? Don’t! Python programming language teaching from Simpliv puts you right there to be able to write Python programs with ease. Place object-oriented programing in a Python context and use Python to perform complicated text processing.