Idiomatic "for" Loops
Here’s a code snippet showing the example code used in this lesson:
clouds = ["Stratus", "Cumulus", "Cirrus", "Alto", "Nimbus"]
# Bad: Using the list index
# for i in range(len(clouds)):
# print(clouds[i])
# Good: Pythonic for-loops
for cloud in clouds:
print(cloud)
00:00
In this final lesson that introduces you to how to write idiomatic code in Python, you’re going to learn about writing Pythonic for
loops.
00:09
This is one of the most common, somewhat awkward, constructs that people coming from other languages to Python use when they create for
loops—they write something like this, where you would iterate over the index of a range object that kind of gets constructed by taking the length of an iterable. In this case, that’s the clouds
list up here.
00:30 And then you want to access each of those items by their index and again reference the original list in here. And this works fine. I’m going run it to prove that to you as well.
00:42 You can run this code and you get the expected output. It loops over all the clouds in here and prints out each one of them. But there’s a easier and more Pythonic way of writing this same construct,
00:59
and it looks like this. Python has this idea of a for-each loop where you just iterate directly over the items in an iterable. So, if I write a for
loop in Python, I can just say “For each item in here,” which I’m naming here cloud
—so, “For each cloud
in clouds
, print out the cloud
.” And this construct reads essentially like an English sentence.
01:22
You can just say for cloud in clouds:
print(cloud)
, which is much more understandable than if you would say something like for i in range(len(clouds)):
print(clouds[i])
, but it achieves the same thing. This is the more Pythonic way of writing it, and let me prove to you also that it works in the same way.
01:43 So if I run this script again, you can see that I get the same output here. Each cloud is printed separately on its own line with a Pythonic iteration over this iterable here.
01:57 And this concludes this short course on writing Pythonic code. In the next and final lesson, you’re going to go over all of the different topics that you touched on and what you learned in this course.
Become a Member to join the conversation.