Write Pythonic Code Like a Seasoned Developer Transcripts
Chapter: Pythonic Loops
Lecture: Wait, is there a numerical for loop (v2)?
0:01 So in some sense we saw that range gives us a kind of a numerical "for" loop
0:04 and that lets us walk through numbers from some starting point
0:08 to some ending point, evenly incrementing them, continuously by the same amount.
0:12 If you actually want to get items out of a collection,
0:15 if you are going to emulate that original "for" loop
0:17 where you say "I am going to get the index
0:18 and then index into some kind of collection like a list or something", still,
0:22 don't do that, don't do that with the range, there is yet a better way.
0:26 So sometimes you want the item and you need the index
0:29 at which that item comes from,
0:31 suppose you are making like an ordered list type thing,
0:33 item number 1 is this, item number 2 is that and so on,
0:36 that might look kind of like this fake "for" loop up here, right,
0:40 so we create the index, we do the loop based on the index,
0:43 we get the value and we print out the index and value.
0:46 We can use a really cool combination of tuple unpacking
0:49 and a special type of iterable that we can work with,
0:52 so simulate this in a much more Pythonic way,
0:54 so if we wanted to write this code we could write something like "for",
0:57 let me just suspend what goes here for a minute,
0:59 "something in" we can say "enumerate"
1:01 and when you enumerate some kind of collection like in this case
1:03 we'll enumerate "data", so what actually comes out is a tuple of 2 items,
1:08 first the index and then the value for that part,
1:11 to the loop, so we can unpack that in two variables right here,
1:14 index and value and then we can do whatever we are going to do,
1:17 here we said something like this: "we'll print out the index and the value",
1:23 there you have it, if we are going to make this sort of ordered list style,
1:26 you might put a "+1" here, item 1 goes to 1, item 2 is 7, item 3 is 11.
1:31 There, that's the Pythonic way to do numerical "for" loops.
1:35 So we saw that range works for just walking through a set of numbers,
1:38 but if you actually want to get the items and the numbers,
1:41 or items and the indexes rather, use enumerate
1:43 and unpack the tuple into the indexing value and it can't be easier.