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 !

python tutorial

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

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

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Python Programming Tutorials For Beginners

Python Programming Tutorials For Beginners

Python Modules Tutorial - Python Tutorial for Beginners

This Edureka session on Python Modules Tutorial will help you understand the concept of modules in python, why, and how we can use modules in Python.

Standard Data Types in Python - Python Tutorial - Python Training

This video on 'Standard Data Types in Python' will help you establish a foothold on Python by helping you learn basic concepts.

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Python Datetime Tutorial: Manipulate Times, Dates, and Time Spans

Become a master of times and dates in Python as you work with the datetime and calender modules in this data science tutorial.