Python For Loops
Python's for is "for each" — it iterates over any iterable: list, tuple, set, dict, string, file, generator, range, anything with __iter__.
Iterating
PYTHON
for f in ['apple', 'banana', 'cherry']:
print(f)
for ch in 'abc':
print(ch)
for line in open('hello.txt'):
print(line.rstrip())
range — the counted loop
PYTHON
for i in range(5): # 0..4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)
enumerate & zip
PYTHON
for i, name in enumerate(['Ada', 'Grace', 'Linus'], start=1):
print(i, name)
for name, age in zip(['Ada', 'Grace'], [36, 56]):
print(name, age)
break / continue / else
PYTHON
for n in [2, 4, 6, 7, 8]:
if n > 6:
break
if n % 2:
continue
print(n) # 2, 4, 6
else:
print('would print if we didn\\'t break')
Comprehensions
Often the most Pythonic replacement for a for-loop building a collection:
PYTHON
squares = [n * n for n in range(10)]
unique = {word.lower() for word in words}
by_id = {u['id']: u for u in users}
Tip: Don't modify a list while iterating over it. Iterate a copy (
for x in list(items):) or build a new list instead.Example
Example
for i in range(5):
print(i)
for i, name in enumerate(['Ada', 'Grace', 'Linus']):
print(i, name)
Try it Yourself »
Exercise
Iterate yielding (index, value) pairs.
for i, v in
(items):
print(i, v)
Nine letters.
Discussion
Loading…