ruk·si

🐍 Python
Loops

Updated at 2018-06-09 17:51

Learn to write Pythonic loops.

loot = ['sword', 'axe', 'staff']

for item in loot:
    print(item)

for i, item in enumerate(loot):
    print(f'{i}: {item}')

effects = {
    'sword': '+1 attack',
    'axe': '+2 attack',
    'staff': '+3 magic',
}

for name, effect in effects.items():
    print(f'{name}: {effect}')

Prefer enumerate over counting items.

# bad
names = ['Safe', 'George', 'Mildred']
count = 0
for name in names:
    print(count, name) # 0 Safe, 1 George, 2 Mildred
    count += 1

# good
names = ['Safe', 'George', 'Mildred']
for i, name in enumerate(names):
    print(i, name) # 0 Safe, 1 George, 2 Mildred

for/else will run if loop runs to completion without a break while/else will also only run if loop runs to completion without a break

for flavor in ['apple', 'banana', 'chocolate']:
    if flavor == 'banana':
        break
else:
    raise ValueError('no banana flavor found')

# => ok

for flavor in ['apple', 'vanilla', 'chocolate']:
    if flavor == 'banana':
        break
else:
    raise ValueError('no banana flavor found')

# ValueError

While-loops.

x = 0
while x < 4:
    print(x)
    x += 1

Use while 1 for infinite loops. It is faster than while True, but rarely significant boost.

x = 0
while 1:
    print(x)
    x += 1
    if x > 10:
        break

Iterate collections using in if they support it. Use if ... in ... and for ... in .... You may implement if in with __contains__ method. You may implement for in with __iter__ method.

# bad
name = 'Safe Hammad'
if name.find('H') != -1:
    print('This name has an H in it!')

# good
name = 'Safe Hammad'
if 'H' in name:
    print('This name has an H in it!')
# bad
pets = ['Dog', 'Cat', 'Hamster']
i = 0
while i < len(pets):
    print('A', pets[i], 'can be very cute!')
    i += 1

# good
pets = ['Dog', 'Cat', 'Hamster']
for pet in pets:
    print('A', pet, 'can be very cute!')

Source

  • Python Tricks The Book, Dan Bader
  • Fluent Python, Luciano Ramalho