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

Login or purchase this course to watch this video and the rest of the course contents.
0:01 So it turns out sometimes when you really do just want to
0:04 work through a sequence from numbers, in order 1, 2, 3, 4,
0:07 or maybe even evens for some reason, 0, 2, 4, 6, and so on,
0:11 so in Python we actually do avoid to do this,
0:14 so over here imagine we wanted this code that went from 0 up to 10
0:17 but not including it, what do we do, remember,
0:20 there is no for loop so we just say for i in
0:24 and we can create this generator that goes from 0 to 10,
0:28 and we could even use the step size if we wanted to change
0:31 the increment there instead of +=1 we would do something else.
0:35 All right, so this should go from 0 to 9 in the print out.
0:38 And it does, so here we can use range,
0:40 now range is considered slightly dangerous for large values here,
0:44 in Python 2 because if we look at range,
0:50 like so, it just says range 1 to 7 let's put a new line here, like so,
0:54 it says just 1 to 7, this is technically a generator,
0:57 but if we did this in Python 2
1:06 up here you can see this has just been Python,
1:09 which is Python 2, what we'll get at the bottom is no longer a generator it's a list,
1:13 so if you put 10 million here instead of using the generator
1:16 with the yield slowly create this it actually generates a list of 10 million items.
1:21 All at once. And then, lets you loop over it, not amazing right,
1:24 but in Python 3 this is no problem, if you want to do this in Python 2,
1:28 x range is your friend, now you get basically the equivalent of Python 3 range.
1:35 Great, so if you really want to step through numbers,
1:38 just use range that gives you something that's iterable
1:41 and you use that in a foreign loop.
1:44 Yeah, so in some sense there is a way to do a numerical for loop
1:47 it's just not a language construct, it's an idiom.