Pythonic For Loops
In languages like C or Java, loops keep track of an index manually and increment it on every loop iteration. Loops in Python are different. Pythonic loops don’t need to keep track of an index because they can do this automatically.
This is the correct way to write for
loops:
candies = ['Snicker', 'Kitkat', 'Twix', 'Mars']
for candy in candies:
print candy
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
00:00
And finally, we have for
loops. Now in most other languages when you’re dealing with for
loops, you end up doing things like using an index to get you the range. Just for example, here we have a list of candies
. We get the length of that list, and then we pass that to range()
. range()
will produce
00:20
a set of numbers between 0
and 4
, which we’ll then index to use to access the list of candies
. Again, this is a completely valid way of doing this, but in Python you can do a little bit of a better job and you can use the for-each statement in Python.
00:40
And this simply says “For each candy
in listed_things
, print candy
.” So it means “Go through each of the items in this list and do something.” And in this case, all we’re doing is printing.
00:53
It produced the same result. This is much cleaner and much easier to understand for many reasons. No having to bother with introspection, no need to do this annoying len()
nested inside a range()
.
01:07 So, this ends our idiomatic talk. I hope this was useful to you beginners.
Peter D K on April 1, 2019
Hello Thanks, understood and could tell you know topic in-depth. Just a little slower with presentation speed. Regards Peter
mikesult on Feb. 24, 2020
Thanks for tips on writing Pythonic code. Very helpful.
dragonfly7 on March 29, 2020
These snippets will help to produce more pythonic code !
If I#m not wrong python 2 syntax used, right ?
Ghani on Oct. 28, 2020
Very useful but perhaps a bit too quick presentation? Many thanks!
Walid on Jan. 16, 2021
it would be more useful if we continue this series in reviewing real popular projects and evaluate their code (code reviews/walk through) also quizzes that asks us to select between which is a better code.
Become a Member to join the conversation.
Daniel on March 21, 2019
Enjoyed the series!