Write Pythonic Code Like a Seasoned Developer Transcripts
Chapter: Pythonic Loops
Lecture: Wait, is there a numerical for loop (v2)?

Login or purchase this course to watch this video and the rest of the course contents.
0:01 So in some sense we saw that range gives us a kind of a numerical "for" loop and that lets us walk through numbers from some starting point
0:09 to some ending point, evenly incrementing them, continuously by the same amount. If you actually want to get items out of a collection,
0:16 if you are going to emulate that original "for" loop where you say "I am going to get the index
0:19 and then index into some kind of collection like a list or something", still, don't do that, don't do that with the range, there is yet a better way.
0:27 So sometimes you want the item and you need the index at which that item comes from, suppose you are making like an ordered list type thing,
0:34 item number 1 is this, item number 2 is that and so on, that might look kind of like this fake "for" loop up here, right,
0:41 so we create the index, we do the loop based on the index, we get the value and we print out the index and value.
0:47 We can use a really cool combination of tuple unpacking and a special type of iterable that we can work with,
0:53 so simulate this in a much more Pythonic way, so if we wanted to write this code we could write something like "for",
0:58 let me just suspend what goes here for a minute, "something in" we can say "enumerate" and when you enumerate some kind of collection like in this case
1:04 we'll enumerate "data", so what actually comes out is a tuple of 2 items, first the index and then the value for that part,
1:12 to the loop, so we can unpack that in two variables right here, index and value and then we can do whatever we are going to do,
1:18 here we said something like this: "we'll print out the index and the value",
1:24 there you have it, if we are going to make this sort of ordered list style, you might put a "+1" here, item 1 goes to 1, item 2 is 7, item 3 is 11.
1:32 There, that's the Pythonic way to do numerical "for" loops. So we saw that range works for just walking through a set of numbers,
1:39 but if you actually want to get the items and the numbers, or items and the indexes rather, use enumerate
1:44 and unpack the tuple into the indexing value and it can't be easier.


Talk Python's Mastodon Michael Kennedy's Mastodon