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:08 Let's start with the basics.
0:10 There is no numerical loop in Python,
0:13 there is no for loop, like C++, CSharp, 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<len(data); i++
0:29 we are going to go work with items.
0:31 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.
0:48 Perfect. 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:59 what that might look like, well as you saw we can well,
1:04 first of all, this just put any ideas out of your head, this doesn't round right, obviously.
1:07 There is not for loop, but we can fake this idea
1:09 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:32 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:56 let's put a new line in between, there, 1, 7, 11, perfect.
2:02 No fuss, no muss, just go.
2:06 So, there is no numerical for loop of faking it like this, also not Pythonic,
2:11 we'll talk about what you can do when you really need that later,
2:15 but typically,w rite loops like this.
2:18 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.