Beautiful looping in Python

This article is the first article of the "Writing beautiful and Idiomatic Python code" serie. I'm gonna talking about idiomatic ways for looping using Python.

Obs.: Code quality / design is subjective, feel free to disagree and comment down bellow different approaches and alternatives ways to do the same thing

Summary

Loop over a numeric interval

Don't:

for i in [1, 2, 3, 4, 5]:
    print(i ** 2)

Do:

for i in range(6):
    print(i ** 2)

Loop over a collection

Don't:

colors = ["red", "green", "blue", "yellow"]
for i in range(len(collection)):
    print(colors[i])

Do:

colors = ["red", "green", "blue", "yellow"]
for color in colors:
    print(color)

Loop over a collection and indices

Don't:

colors = ["red", "green", "blue", "yellow"]
for i in range(len(collection)):
    print(i, "--->", colors[i])

Do:

colors = ["red", "green", "blue", "yellow"]
for index, color in enumerate(colors):
    print(index, "--->", color)

Loop over a collection in reverse order

Don't:

colors = ["red", "green", "blue", "yellow"]
for i in range(len(colors) -1, -1, -1):
    print(colors[i])

Do:

colors = ["red", "green", "blue", "yellow"]
for color in reversed(colors):
    print(color)

Loop over two collection at the same time

Don't:

colors = ["red", "green", "blue", "yellow"]
names = ["Hicaro", "Julia", "Fred", "Jake", "Mike"]

n = min(len(colors), len(names))

for i in range(n):
    print(colors[i], names[i])

Do:

colors = ["red", "green", "blue", "yellow"]
names = ["Hicaro", "Julia", "Fred", "Jake", "Mike"]

for color, name in zip(colors, names):
    print(color, name)

An alternative way is to use izip() for gigantic lists (appropriate option in terms of performance's tradeoffs)

colors = ["red", "green", "blue", "yellow"]
names = ["Hicaro", "Julia", "Fred", "Jake", "Mike"]

for color, name in izip(colors, names):
    print(color, name)

Loop over a list in orderly fashion

Do:

names = ["Hicaro", "Julia", "Fred", "Jake", "Mike"]
for name in sorted(names):
    print(name)

Unless you want the list sorted before the loop, you can do this above.

Loop over a dictionary

Do:

info = {"Name": "Hicaro", "Age": 18, "Tel": 2319321931-1}

for key, value in info.items():
    print(f"{key} --> {value}")

References

19