Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Use enumerate() to Keep a Running Index

In the last lesson, you saw how you can make your loops more Pythonic by iterating over items from a container directly, but what if you need to keep track of the item index?

In this lesson, you’ll see how you can use enumerate() to keep track of a running index the Pythonic way. enumerate() is a generator that returns a running index as well as the actual element or item in the container.

AMithKS on July 21, 2019

Can I customize enumerate() for any container like a binary tree, where the index-like value is equivalent to node value?

Wartem on Aug. 25, 2022

As far as I know, range(len) is faster than enumerate() although not considered Pythonic. I use enumerate() because experts say so but it feels awkward with i, _

Become a Member to join the conversation.