Writing Python Code in a Pythonic Way Part-1: loops
When I see a code snippet like the following, that's an example of someone trying to write python like its C.
You can argue whats is it exactly that makes it unpythonic. there are two reasons for it:
- It keeps track of index ‘i’ manually.
- It uses len function to get the size of list letters.
Python is intelligent enough to do the above two tasks automatically. Rather than incrementing index ‘i’ manually on each loop iteration, I could take advantage of the range() function and write something like this:
This is much better but it still can be improved. this loop looks closer to java style. When you see code that uses range(len(…)) to iterate over a container you can usually simplify and improve it further.
Python for loops and like for-each loops that can iterate over items in a container or sequence. So we can write it like this:
Now you can argue that what If I need index also. It is possible to write loops in python that gives you index while avoiding range(len(…)) pattern. The enumerate() built-in function helps you here and is pythonic as well.
Now let’s say you really need to write a C-style loop in which you can control the step size of the index like below:
In such a situation we can use our friend range() function which accepts optional parameters to control the start value(a), the stop value(n) and the step size(s) in a loop. We can write the above code like this:
Writing C-style loops in python are viewed as unpythonic. It is better to avoid managing loop indexes and stop conditions manually if possible.
Always view python for loops as a for-each loop that can iterate directly over the items of a container or a sequence.
Courtesy: Python tricks: The book Dan bader