Write Pythonic Code Like a Seasoned Developer Transcripts
Chapter: Pythonic Loops
Lecture: There is no numerical for loop

Login or purchase this course to watch this video and the rest of the course contents.
0:01 Loops in Python are a little bit different than loops in other languages.
0:04 You'll see that there is much more collections philosophy underlying them.
0:07 Let's start with the basics.
0:09 There is no numerical loop in Python,
0:11 there is no "for" loop, like C++, C#, Java, Javascript,
0:16 they have this way of walking through a number and incrementing it
0:19 usually to pull items out of an array, so I imagined what would that look like in Python
0:23 if we had a numerical "for" loop, something like: "this for i = 0; i less than len(data); i++ "
0:29 we are going to go work with items.
0:30 Well, that doesn't exist. Sometimes,
0:34 people try to work their way around it using the loops
0:36 that do exist and recreating this more or less.
0:40 Look, we've done it, we've taken the initialization of the variable, moved before loop,
0:44 we have the test and now withing the body loop we do the increment. Perfect.
0:48 No, technically that works but this is also super non-Pythonic
0:52 so let's look at some code that is.
0:55 All right, here in PyCharm you can see I kind of sketched out
0:57 what that might look like, well as you saw we can well,
1:01 first of all, this just put any ideas out of your head, this doesn't round right, obviously.
1:07 There is no "for" loop, but we can fake this idea
1:10 we can say the "i = 0" goes here, this can be a "while" loop,
1:14 we can do our test there and this increment bit, we can put that down here.
1:20 Like so, we don't have "++" but we do have a "+= 1", let's see if it works,
1:24 it should put out 1 and 7 then 11, oh but of course, it does not, let's do this.
1:33 Now it prints out the index and it prints out the value.
1:36 All right, this is not Pythonic, so we'll just make a note: "No, NOT Pythonic".
1:43 So of course, what is the proper way to loop through these items?
1:46 "for item in the collection" and let's print this out,
1:52 instead of worrying about the index, we just have the item
1:55 let's put a new line in between, there: 1, 7, 11. Perfect.
2:02 No fuss, no muss, just go.
2:05 So, there is no numerical "for" loop or faking it like this, also not Pythonic,
2:11 we'll talk about what you can do when you really need that later,
2:14 but typically, write loops like this.
2:17 OK, in a graphic, no numerical "for" loop,
2:20 instead just loop over the data, usually the goal is to get at the underlying items
2:24 and some sequence anyway.