Loops
A loop repeats a block of code. for walks an iterable one item at a time. while repeats as long as a condition stays true. Both can use break, continue, and an else clause that runs when the loop was not broken.
Detailed Explanation
Most work in a program is "do this for each record". Python's default tool for that is for item in iterable:. The iterable can be a list, a file, a dict, a generator, or anything that implements the iterator protocol. On each pass the next value is bound to item and the body runs. You do not manage an index unless you need one.
When you do need an index, use enumerate(items, start=0) rather than range(len(items)). When you need two sequences in lockstep, use zip. When you need a numeric range, use range(stop) or range(start, stop, step). range is not a list; it is a lazy sequence that stores three numbers.
while is for loops whose end is a condition rather than a collection: read until a socket closes, retry until a lock is free, poll until a job finishes. The condition is checked before each iteration. If it is already false, the body never runs. A while True: with an internal break is the usual way to write "loop until we decide to stop".
break leaves the loop immediately. continue skips the rest of the current iteration and goes to the next. else on a loop is a separate feature: the else block runs if the loop finished without a break. It exists so you can write a search without a flag variable.
Loop variables leak. After for user in users:, user is still bound to the last item. After a loop that never ran, the name is unbound if it was not bound before. Comprehensions do not leak in Python 3; for loops do.
Nested loops are legal and expensive. An inner loop over n items inside an outer loop over n items is O(n²). If you find yourself scanning a list on every outer pass to answer "have I seen this?", replace the inner scan with a set.
Prefer iterating the object you have. Iterating a dict yields keys. for key, value in table.items(): yields pairs. for line in open(path): yields lines and should live inside with. Do not call list() on a huge iterable just to loop; that forces the whole thing into memory.
Code Examples
skus = ["A-1", "B-2", "C-3"]
for index, sku in enumerate(skus, start=1):
print(index, sku)
# 1 A-1
# 2 B-2
# 3 C-3
# zip stops at the shortest input.
prices = [9.5, 4.0]
for sku, price in zip(skus, prices):
print(sku, price)
# A-1 9.5
# B-2 4.0# while: retry until the condition fails.
attempts = 0
connected = False
while attempts < 3 and not connected:
attempts += 1
connected = attempts == 2 # succeed on the second try
print(attempts, connected) # 2 True# else on a loop runs only when no break fired.
needles = ["ada", "linus"]
for name in needles:
if name == "grace":
print("found")
break
else:
print("not found") # not foundCommon Gotchas
Do not mutate a list you are iterating
`for item in batch: batch.remove(item)` skips elements. Iterate a copy, or build a new list.
`for k in mapping` yields keys, not pairs
write `.items()` when you need values. Iterating a dict while inserting new keys can raise `RuntimeError`.
Loop names leak
a later `print(item)` after the loop shows the last value, which is a common closure bug inside functions defined in the loop. Bind a default argument if you need the current value.
`range` is empty when start >= stop with a positive step
`range(5, 5)` produces nothing, not an error.