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:09 to some ending point evenly increment 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:18 before you say I am going to get the index
0:20 and then index into some kind of collection like a list or something still,
0:23 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
0:30 at which that item comes from,
0:32 suppose you are making like an ordered list type thing,
0:35 item number 1 is this, item number 2 is that and so on,
0:37 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,
0:43 we get the value and we print out the index and value.
0:47 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:55 so if we wanted to write this code we could write something like 4,
0:58 let me just suspend what goes here for a minute,
1:00 something and we can say enumerate
1:02 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,
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:15 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:23 there you have it, if we are going to make this sort of ordered list style,
1:27 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:44 and unpack the tuple into the indexing value and it can't be easier.