Use enumerate() to Keep a Running Index – Real Python (original) (raw)
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.
00:00 Now, maybe you’re wondering, “What should I do if I need the item index?” Right? You might not always be able to rewrite your loops that way, with a for-each loop, if you actually need the item index.
00:12 And thankfully, there’s a Pythonic way to keep that running index that allows us to avoid this kind of odd-looking range of length of something construct.
00:25 And for that, we have the built-in enumerate() function. So as you can see here, I’ve changed this for loop a little bit. So now, I’m calling enumerate() on this list here, and enumerate() is another generator.
00:37 What it’s going to do is it’s going to return a running index and then also the actual element. And you can see that here. So, it’s returning the index first, and then the actual item in that container.
00:49 So it’s, well, enumerating the container. And I can take advantage of that. If I ever need the actual index, I can use enumerate() and that would be the Pythonic way to deal with this situation, versus keeping track of that index manually.
01:04 Let’s take a look at what this does when we actually run it. All right, so this iterated over the whole container and it was keeping track of a running index, and it was also printing each item individually. So again, enumerate() is very handy for those kinds of situations.