Iterate Over a Container Directly
In the last lesson, you saw how you could start to make your loop more Pythonic by not keeping track of the loop index manually, but your loop can still be refactored to be more Pythonic.
In this lesson, you’ll learn that for
loops in Python are like “for each” loops in other languages. You can use them to iterate over items from a container or sequence directly and don’t have to look up each item by index.
00:00 Now, if you took this refactored loop and you showed it to a Python programmer, they would probably cringe a little bit because this is really not ideal yet.
00:09
This could be simplified further. I mean, we’re a little bit better because we got rid of this manual index tracking, but there’s more we can do. So actually, a key thing to realize is that for
loops in Python are really more like for-each loops in other languages.
00:26
You can use them to iterate over items from a container or sequence directly, and you don’t have to look up each individual item by index. So, I can take this loop and simplify it even further by taking advantage of that. This is what it would look like: I would just go for item in my_items
, which is nice because now we’re actually giving a real name to this variable here, calling it item
. We completely got rid of the i
and the indexing here, and this is going to work just the same.
00:57
So, this implementation is much more Pythonic. It got rid of the need to actually use the range()
builtin. We’re not having to call len()
to get the length of that list, but instead, we’re just going to iterate over that container and the container itself is going to take care of handing out these elements so we can process them. So, if the container is ordered, like in a list, the resulting elements that we’re iterating over are also going to be ordered.
01:21 And if the container is not ordered, then it will return the elements kind of in an arbitrary order. So, this is going to give us all the elements, but there’s no guarantees how we’re iterating over them, depending on the container that you use. But these two examples here, because we’re dealing with a list, they are exactly the same.
01:39 Like, we’re getting exactly the same resulting printout here.
Become a Member to join the conversation.