Sub topic 3
Nested loops
Assume you know Python variables, indentation, lists, strings, integers, and how to run a Python 3 script.
Nested loops
A nested loop is a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.
for row in range(1, 4):
for column in range(1, 4):
print(row * column, end=" ")
print()The outer loop selects a row. The inner loop prints three values for that row. The output is:
1 2 3
2 4 6
3 6 9The loop `else` clause
A loop’s else block runs when the loop finishes normally. It does not run when break stops the loop.
for number in range(2, 10):
for divisor in range(2, number):
if number % divisor == 0:
break
else:
print(number, "is prime")The inner else runs only when no divisor causes break. Therefore, it prints 2, 3, 5, and 7.
Do not modify a list while looping
Removing or adding items changes the positions that the loop is visiting. This can skip items or produce surprising results.
numbers = [2, 4, 6, 8]
for number in numbers:
numbers.remove(number)
print(numbers) # [4, 8]Build a new list instead:
numbers = [2, 4, 6, 8]
numbers = [number for number in numbers if number % 2 != 0]
print(numbers) # []How `for` works internally
Python calls iter() once to obtain an iterator. It then calls next() repeatedly. When next() raises StopIteration, the loop ends.
iterator = iter(["a", "b"])
print(next(iterator))
print(next(iterator))
try:
next(iterator)
except StopIteration:
print("finished")Comprehensions
A list comprehension is a compact way to create a list from a loop and optional condition.
squares = [number * number for number in range(5)]
print(squares) # [0, 1, 4, 9, 16]Use a regular loop when the operation has several steps or side effects.
Common `range()` mistakes
range() excludes its stop value. Thus, range(1, 4) produces 1, 2, and 3. A zero step raises ValueError, and a negative step requires a start value greater than the stop value.
Exercise
When does a loop's else block run?
Show answer
It runs when the loop finishes without encountering break, including when the iterable is empty.