For Each Loops in Python with enumerate() and range()

Published: 14 March 2017
on channel: Real Python
33k
689

► Write clean and Pythonic for, while, and "for each" loops in Python

One of the easiest ways to spot a developer with a background in C-style languages who only recently picked up Python is to look at how they loop through a list.

In this tutorial you'll learn how to take a "C-style" (Java/PHP/C/C++) loop and turn it into a nice and "native" Python loop.

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 to avoid having to keep track of loop indexes manually.

The main takeaways in this tutorial are:

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

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

Read the complete tutorial at →

To get more Python Tricks and to discover the full potential of Python check out "Python Tricks: The Book" at the link below.

FREE COURSE – "5 Thoughts on Mastering Python"

PYTHON TRICKS: THE BOOK

SUBSCRIBE TO THIS CHANNEL:

* * *

► Python Developer MUGS, T-SHIRTS & MORE:

FREE Python Tutorials & News:
» Python Tutorials:
» Python News on Twitter:
» Weekly Tips for Pythonistas:
» Subscribe to this channel:


Watch video For Each Loops in Python with enumerate() and range() online, duration 09 minute 45 second in high hd quality that is uploaded to the channel Real Python 14 March 2017. Share the link to the video on social media so that your subscribers and friends will also watch this video. This video clip has been viewed 33 thousand times and liked it 689 visitors.