How to Write Pythonic Loops

One of the easiest ways to spot a developer who has a background in C-style languages and only recently picked up Python is to look at how they loop through a list. In this course, you’ll learn how to take a C-style (Java, PHP, C, C++) loop and turn it into the sort of loop a Python developer would write.

You can use these techniques to refactor your existing Python for loops and while loops in order to make them easier to read and more maintainable. You’ll learn how to use Python’s range(), xrange(), and enumerate() built-ins to refactor your loops and how to avoid having to keep track of loop indexes manually.

The main takeaways in this tutorial are that:

  1. Writing C-style loops in Python is considered not Pythonic. Avoid managing loop indexes and stop conditions manually if possible.

  2. Python’s for loops are really “for each” loops that can iterate over items from a container or sequence directly.

What’s Included:

Related Learning Paths:

About Dan Bader

Dan Bader is the owner and editor in chief of Real Python and the main developer of the realpython.com learning platform. Dan has been writing code for more than 20 years and holds a master's degree in computer science.

» More about Dan

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Participant Comments

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.

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 :)

David Mellor on July 25, 2019

Brilliant - I knew this already, but to add a perspective of another language was very useful!

« Browse All Courses