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.

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:

C-loop

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

Conclusion

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
deepak sharma

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.