Idiomatic Python — Part One, Looping Over Collection
The Term Idiomatic Python I heard for the first time from the video of Raymond Hettinger in youtube. That video is really amazing for me, the way he explains the material and the difference between one and another approach to solve one problem is fascinating. In order to make it more easier to access the syntax from this video, I made this article.
“Python Idioms for people coming from other languages and how to improve your idiomatic practices with Python.”
quoted from: https://realpython.com/courses/idiomatic-python-101/
Okay, let start by a simple example that has been explained from that video, to iterate over collection in another programming languages such as C++ or Java, usually, we use #bad version in python as shown in the code below. In, python it is faster and cleaner to use #good version in the code below. Instead of using range and find the length of the color list, we just iterate over the list using color in colors.
How about the backward loop? do we have the idiom for it?
Yes, we have it. As is shown below, the #good version use function reversed(colors) to reversely iterate over the list. In other hands, the #bad version for me look very ugly hahaha 😄
Next…
When we need both the index and the value of the list, use enumerate to iterate over it. As usual, it is faster and cleaner.
And for the last in this article, if you want to iterate over two collections at the same time, use zip other than #bad version in code below. It is cleaner and faster in python.
Sharing is Caring, share if you feel it good for you
Okay guys, wait for the next article about Idiomatic Python to for me to publish it. Thanks for reading, share it if you feel it better share it.