How to Write Pythonic Loops: Overview
One of the easiest ways to spot a developer who has a background in C-style languages and only recently picked up Python is to look at how they loop through a list. In this course, you’ll learn how to take a C-style (Java, PHP, C, C++) loop and turn it into the sort of loop a Python developer would write.
In this lesson, you’ll look at the sort of loop you might expect a developer coming from a C-style language to write in Python. Next, you’ll look at ways in which you can fix this loop in order to make it more Pythonic.
00:00 Hey there, this is Dan Bader. And today I want to talk about how you can make your loops more Pythonic. I know a lot of people are migrating to Python from different language backgrounds, and one of the things that makes it very easy to spot someone with a background in, let’s say, a C-style language—like C, C++, Java, C#—what makes them very easy to spot is how they write their loops. In this case here, I’ve got this list with three items, and I want to iterate over that so I can print out each item. This is the end result we want to get, here.
00:38 And if you see someone writing a loop like this in Python—let’s say, during an interview situation, or when you’re reviewing someone’s code—it becomes very clear that this person is not super familiar with how a loop like that would be written in Python.
00:54 It looks like a C-style, Java-style loop, right? We’re keeping track of this index variable here, and we’re taking the length of that list to iterate over it, and then we’re also accessing each element based on the index, and of course, we need to keep track of our loop variable here—so, not very Pythonic.
01:15 So what I’m going to do in this video is I’m going to go over this loop and I’m going to refactor it. I’m going to go over all of these items that I just called out and I’m going to make sure we’re going to make this loop as Pythonic as possible, and really make this seem like a loop that a native Python developer would have written.
Become a Member to join the conversation.
muralichintapalli on Aug. 13, 2019
How do i install click module for ubuntu machine with Python3.5 ?