How to Write Pythonic Loops: Conclusion
In this course, you learned how to write loops like a Python developer. Keep in mind that writing C-style loops is considered not Pythonic. If possible, try to avoid managing loop indexes and stop conditions manually.
Also remember that for
loops in Python are like “for each” loops in other languages, so you can use them to iterate over a container or sequence directly.
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 Now to wrap this up, I just want to reiterate some of the key points in this video. So first of all, writing C-style loops in Python is considered un-Pythonic.
00:10
It’s not a very natural way to do that in Python, and so if possible, you should try and avoid managing loop indexes and these stop conditions manually. The other thing is that Python’s for
loops are really for-each loops, so they can iterate over items from a container or a sequence directly, and just kind of consume items from that container and then hand them to you.
00:32 And you should really take advantage of that if you’re writing Python code because then you don’t need to manage all of these indexes, index lookups, and keeping track of that manually—you don’t have to do that.
00:45 Python will do it for you, and that way you can reduce the amount of code you need to write, the amount of code you need to manage. That’s a great way for you to simplify your programs. And using these Python-style loops also makes it harder to introduce bugs, right?
00:59 You can’t really be off by one, or you can’t be running past the end of a container if you’re using a for-each style loop. So I would really encourage you to use them. Cool! Well, best of luck and happy Pythoning!
Vignesh on July 16, 2019
Good one, making me think in simpler way
Daniel Galvan on July 19, 2019
Thank you Dan! Great refresher
aradim on July 20, 2019
Thank you very much, Nice!
Peter Ott on July 22, 2019
👌
Beni on July 22, 2019
Thank you~ So benefit, …^*^
Rob H on July 23, 2019
Great tip, thanks much Dan!
David Mellor on July 25, 2019
Brilliant - I knew this already, but to add a perspective of another language was very useful!
ALXTheMaster on July 31, 2019
Thanks A lot
Balaje on Aug. 1, 2019
Awesome! Just a quick question, to develop the decremented logic in for loop, should I provide step parameter with the negative value? Can you please suggest me
brunofl on Aug. 4, 2019
This was perfect, I ways had doubts on how to properly implement a c / java style loop the pythonic way :)
Lijo Joseph on Aug. 11, 2019
Loved it!!
Anonymous on Aug. 15, 2019
Thanks Dan! Python does have a way of making things simple and beautiful!
Dan Bader RP Team on Aug. 15, 2019
Python does have a way of making things simple and beautiful!
I agree! That’s why I find it such an enjoyable language to work with :)
Pygator on Dec. 22, 2019
I will laugh at my friends who write c-style loops of course! Enumerate is very useful at getting that index to use if required.
arjunaraoj on Dec. 27, 2019
nice
alanhrosenthal on March 24, 2020
Thanks. As an Old C Guy, this was very informative. It will probably take a bit of work to overcome my bad habits.
Ajay on April 25, 2020
loved this course, very informative.
Tobi Olusa on June 2, 2020
Quite enlighten.
beingpython on Aug. 23, 2020
Being Pythonic… nice message, interesting content.
Ghani on Oct. 15, 2020
Very interesting tutorial; thanks Dan!
Alexy on Dec. 9, 2020
nice, clear, thanks alot )
JeremyMechEng on Aug. 15, 2022
Thanks for the info!
This may well be covered elsewhere but I’d like to know if nested loops are treated the same? Do they HAVE to be across two lines, or is there a magic one-liner method?
I tried:
my_list = ['a', 'b', 'c']
my_num = [1, 2, 3]
for (item, num) in (my_list, my_num):
print(item, num)
and found ValueError: too many values to unpack (expected 2)
whereas:
for items in my_items:
for num in my_num:
print(items, num)
Yielded the expected result, anyone able to shed some light on this one? Cheers (:
Geir Arne Hjelle RP Team on Aug. 15, 2022
Hi @JeremyMechEng
Python doesn’t have dedicated syntax for nested for loops. However, you can use itertools.product()
to nest your lists and then loop over that product:
import itertools
characters = ["a", "b", "c"]
digits = [1, 2, 3]
for char, digit in itertools.product(characters, digits):
print(char, digit)
realpython.com/python-itertools/#dealing-a-deck-of-cards shows another example of using itertools.product()
.
Martin Breuss RP Team on Aug. 16, 2022
@JeremyMechEng or you could use a list comprehension:
>>> characters = ["a", "b", "c"]
>>> digits = [1, 2, 3]
>>> [print(c, d) for c in characters for d in digits]
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2
c 3
[None, None, None, None, None, None, None, None, None]
Note that in this case it’ll create a list with the return value of calling print()
, which is None
. So it’ll be more interesting if you want to build a list.
Also, complex list comprehensions get messy and hard to understand quickly, so it’s rarely worth it to go into the level of nested loops. It’ll be more readable to write out the nested for
loop instead.
JeremyMechEng on Aug. 19, 2022
@Geir Arne Hjelle @Martin Breuss Thanks both for the answers! Much appreciated
Become a Member to join the conversation.
Abby Jones on July 16, 2019
Very informative as usual!