How to use enumerate() function in Python For Loop

The enumerate() function is often used instead of range() when creating a For Loop in Python. What does this function do exactly, and how to do we use it? We will explore all that and more inside this tutorial.

Of course, the enumerate() function can also be used outside of For loops, so we will be discussing all of its possible use in this article.


Python Enumerate() Function Syntax

Let’s start off by using the enumerate() function in some simple examples.

Unlike most functions, enumerate() has two return types, not one. It takes as an argument an iterable, such as a List or Tuple and returns an enumerable object. This object contains n pair of tuples, where n is the number of values in the original iterable. Each tuple contains two values, the first being an index number, and the second is a value from the original iterable.

If you haven’t figured it out yet, what enumerate() does is attach an “index number” (starting from 0) to each value in the original list/tuple/iterable. This index number increments by one for each value.

Now how does this help? We will get to that soon. Let’s take a look at some output first.

mylist = ["Hello", "World", "I", "am", "CodersLegacy"]

obj = enumerate(mylist)
print(list(obj))
[(0, 'Hello'), (1, 'World'), (2, 'I'), (3, 'am'), (4, 'CodersLegacy')]

As you can see here, we have a list where each value from mylist now has an index number associated with it. Now let’s see how we can use this with For Loops to make life easier for ourselves.


Using enumerate() with For Loops

Often when iterating over a list of objects, we need a counter. This is usually done by using range(), but in certain scenarios this is not possible.

So instead what we do is this.

mylist = ["Hello", "World", "I", "am", "CodersLegacy"]

i = 0
for object in mylist:
    print(object)
    i += 1

But this looks a bit messy and requires extra code. So instead we use enumerate!

This is how it’s done.

mylist = ["Hello", "World", "I", "am", "CodersLegacy"]

for index, object in enumerate(mylist):
    print(index, object)

Here you can see the output:

0 Hello
1 World
2 I
3 am
4 CodersLegacy

As you can see, it’s easy to use, does not need to be imported and is actually faster than using regular for loops!


This marks the end of the How to use enumerate() in Python For Loop Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Leave a Comment