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 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, so in Python we actually do have a way to do this,
0:14 so over here imagine we wanted this code that went from 0 up to 10 but not including it, what do we do? Remember,
0:21 there is no "for" loop, so we just say "for i in" and we can create this generator that goes from 0 to 10,
0:29 and we could even use the step size if we wanted to change the increment there, instead of "+= 1" we would do something else.
0:36 All right, so this should go from 0 to 9 in the print out. And it does, so here we can use range,
0:41 now range is considered slightly dangerous for large values here, in Python 2, because if we look at range,
0:51 like so, it just says range 1 to 7, let's put a new line here, like so, it says just 1 to 7, this is technically a generator,
0:58 but if we did this in Python 2 up here you can see this has just bin/Python,
1:10 which is Python 2, what we'll get at the bottom is no longer a generator, it's a list, so if you put 10 million here instead of using the generator
1:17 with the yield slowly create this, it actually generates a list of 10 million items. All at once. And then, lets you loop over it. Not amazing, right?
1:25 but in Python 3 this is no problem, if you want to do this in Python 2,
1:29 "xrange" is your friend, now you get basically the equivalent of Python 3 "range". Great, so if you really want to step through numbers,
1:39 just use range, that gives you something that's iterable and you use that in a "for...in" loop.
1:43 Yeah, so in some sense there is a way to do a numerical "for" loop, it's just not a language construct, it's an idiom.


Talk Python's Mastodon Michael Kennedy's Mastodon