Writing Python Code in a Pythonic Way Part-1: loops

Pythonic Loops

deepak sharma
3 min readOct 16, 2020


When I see a code snippet like the following, that's an example of someone trying to write python like its C.

Unpythonic loops

You can argue whats is it exactly that makes it unpythonic. there are two reasons for it:

  1. It keeps track of index ‘i’ manually.
  2. 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:

Still Unpythonic

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:

Pythonic Loop

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.

Pythonic loop with index

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:

Pythonic Loop using range


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



deepak sharma

Senior Programmer with 10 years of industry experience. I love to learn and share new things. I have worked on varied tech stacks like Python flask, Elixir etc.