Python Enumerate – Simplify Looping With Counters

Guide to Python Enumerate: A for loop in Python is typically written as a loop that iterates over an iterable object. This means that you can access items in the iterable without using a counting variable. You may, however, want a variable that changes with each loop iteration on occasion. You can use Python’s enumerate() to get a counter and the value from an iterable at the same time instead of creating and incrementing a variable yourself!

Iterating With for Loops in Python

In Python, a for loop iterates through a collection. This means that on each iteration, Python assigns the next item from an iterable to the loop variable, as in this example:

Example 01:

names = ["Preet", "Ranjeet", "Adil"]
for name in names:
    print(name)

Output:

for loop Python Enumerate

names, in this case, are a list of three strings: “Preet,” “Ranjeet,” and “Adil.” Lists are one type of iterable object in Python. The loop variable in the for loop is value. Value is assigned to the next item from values on each iteration of the loop.

After that, you print the value on the screen. Collection-based iteration has the advantage of avoiding the off-by-one error that is typical in other programming languages.

Example 02:

index = 1
for name in names:
     print(index, name)
     index += 1

Output:

img2 Python Enumerate

In this case, the index is an integer that indicates where you are in the list. You print index and value on each iteration of the loop. The loop’s final step is to increment the number stored in an index by one. When you neglect to change the index on each loop, you’ll get this bug:

Example 03:

 index = 1
 for name in names:
     print(index, name)

Output:

img3 Python Enumerate

Because there is no code to update the index’s value at the end of the loop, it remains at 0 on each iteration in this example. This type of issue is notoriously difficult to trace down, especially in long or sophisticated cycles.

Another popular method for solving this problem is to use range() and len() to generate an index automatically. You won’t have to remember to update the index this way:

Example 04:

for index in range(len(values)):
     name = names[index]
     print(index, name)

Output:

img4 Python Enumerate

Len(values) yields the length of values in this case, which is 3. The range() function then constructs an iterator that runs from the default starting value of 0 to len(values) minus one. The index becomes your loop variable in this situation. You set a value equal to the item in values at the current index value in the loop. After that, you output the index and value.

Using Python enumerate()

In a loop, you can use enumerate() in a similar fashion to how you’d use the original iterable object. You put the iterable inside the parenthesis of enumerating instead of just after it in the for loop (). You’ll also need to tweak the loop variable, as illustrated in this example:

Example 05:

for count, name in enumerate(names):
     print(count, name)

Output:

img5

When you call enumerate(), you’ll get two loop variables in return:

  • The current iteration’s count
  • The item’s value in the current iteration.

The loop variables, like those in a standard loop, can be named whatever you like. In this example, count and value are used, but they might be called I and v or any other legal Python names.

Enumerate() in Python provides an extra argument that you can use to alter the count’s initial value. Because Python sequence types are indexed starting with zero, the initial value is set to zero by default. To put it another way, When retrieving the first entry of a list, you use the index 0:

Example 06:

print(names[0])

Output:

img6

As you can see in this example, using the index 0 to retrieve values returns the first element, Preet. There are situations, though, when you don’t want the count from enumerate() to begin at 0. For example, you might wish to give the user a natural counting number as an output. You can adjust the starting count with the start option for enumerate() in this case:

Example 07:

for count, name in enumerate(names, start=1):
     print(count, name)

Output:

img7

In this case, you specify start=1, which sets the value of count to 1 on the first loop iteration. Compare this to the prior examples, where the start was set to 0 by default, to see if you can notice the difference.

Conclusion

When you require a count and the value from an iterable, Python’s enumerate() function helps you create Pythonic for loops. The fact that enumerate() gives a tuple containing the number and value means you don’t have to increase the counter yourself is a significant plus. It also provides you the option of changing the counter’s beginning value.

That’s all for this article. If you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn.

Suggested Articles:

  1. Python Set symmetric_difference() method with Examples

Leave a Comment