19
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
Don't:
for i in [1, 2, 3, 4, 5]:
print(i ** 2)
Do:
for i in range(6):
print(i ** 2)
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)
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)
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)
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)
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.
Do:
info = {"Name": "Hicaro", "Age": 18, "Tel": 2319321931-1}
for key, value in info.items():
print(f"{key} --> {value}")
19