DEV Community


Posted on

Python enumerate(): Simplify Looping With Counters


Table of Contents
• Iterating With for Loops in Python
• Using Python’s enumerate()
• Practicing With Python enumerate()
◦ Natural Count of Iterable Items
◦ Conditional Statements to Skip Items
• Understanding Python enumerate()
• Unpacking Arguments With enumerate()
• Conclusion

A for loop in Python is often written as a loop over an iterable object. To access objects in the iterable, you don't require a counting variable. However, there are situations when you'll want a variable that changes with each loop iteration. You can use Python's enumerate() to get a counter and the value from an iterable at the same time, rather than generating and incrementing a variable yourself!

You'll learn how to:
• Use enumerate() to get a counter in a loop
• Apply enumerate() to display item counts
• Use enumerate() with conditional statements
• Implement your own equivalent function to enumerate()
• Unpack values returned by enumerate()

Python Iteration Using for Loops
In Python, a for loop uses collection-based iteration. This means that on each iteration, Python assigns the next item from an iterable to the loop variable, as in this example:

values = ["a", "b", "c"]

for value in values:

Enter fullscreen mode Exit fullscreen mode


Enter fullscreen mode Exit fullscreen mode

Discussion (0)