LoopingΒΆ

CollectionΒΆ

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

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

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

πŸ’‘ learnt from:

NumbersΒΆ

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

for i in [0, 1, 2, 3, 4, 5]:
    print(i**2)
# Good
for i in range(6):
    print(i**2)

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

πŸ’‘ learnt from:

EnumerateΒΆ

customers = ["Marry", "Thor", "Peter", "Batman"]
for index, customer in enumerate(customers):
    print(f"Customer: {customer}, Queue position: {index}")

index = 0
customers = ["Marry", "Thor", "Peter", "Batman"]
for customer in customers:
    print(f"Customer: {customer}, Queue position: {index}")
    index += 1
# Good
customers = ["Marry", "Thor", "Peter", "Batman"]
for index, customer in enumerate(customers):
    print(f"Customer: {customer}, Queue position: {index}")

# Bad
index = 0
customers = ["Marry", "Thor", "Peter", "Batman"]
for customer in customers:
    print(f"Customer: {customer}, Queue position: {index}")
    index += 1

πŸ’‘ learnt from:

ReverseΒΆ

customers = ["Marry", "Brain", "Peter", "Batman"]
for customer in reversed(customers):
    print(customer)

customers = ["Marry", "Brain", "Peter", "Batman"]
for index in range(len(customers) - 1, -1, -1):
    print(customers[index])
# Good
customers = ["Marry", "Brain", "Peter", "Batman"]
for customer in reversed(customers):
    print(customer)

# Bad
customers = ["Marry", "Brain", "Peter", "Batman"]
for index in range(len(customers) - 1, -1, -1):
    print(customers[index])

πŸ’‘ learnt from:

Two CollectionsΒΆ

names = ["raymond", "rachel", "matthew"]
colors = ["red", "green", "blue", "yellow"]

for name, color in zip(names, colors):
    print(f"{name} --> {color}")

names = ["raymond", "rachel", "matthew"]
colors = ["red", "green", "blue", "yellow"]

n = min(len(names), len(colors))
for i in range(n):
    print(f"{names[i]} --> {colors[i]}")
# Good
names = ["raymond", "rachel", "matthew"]
colors = ["red", "green", "blue", "yellow"]

for name, color in zip(names, colors):
    print(f"{name} --> {color}")

# Bad
names = ["raymond", "rachel", "matthew"]
colors = ["red", "green", "blue", "yellow"]

n = min(len(names), len(colors))
for i in range(n):
    print(f"{names[i]} --> {colors[i]}")

πŸ’‘ learnt from:

SentinelΒΆ

blocks = []
for block in iter(partial(f.read, 32), ""):
    blocks.append(block)

blocks = []
while True:
    block = f.read(32)
    if block == "":
        break
    blocks.append(block)
# Good
blocks = []
for block in iter(partial(f.read, 32), ""):
    blocks.append(block)

# Bad
blocks = []
while True:
    block = f.read(32)
    if block == "":
        break
    blocks.append(block)

πŸ’‘ learnt from: