Looping Until Nothing Changes
Concepts covered: Iteration
When 1 pass is not enough
Some data only settles after several passes, and the number of passes depends on the data. Customer accounts get merged into other accounts, and those accounts get merged again: a into b, b into c, c into d. Replacing each account's target with its target's target shortens every chain. A long chain needs that step repeated. The loop for this job keeps making full passes until a pass changes nothing.
changed = True
while changed:
changed = False
for item in data:
if needs_fixing:
fix_item
changed = TrueThe pattern comes down to 3 lines. changed starts as True so the first pass runs. It resets to False at the top of each pass, so a pass reports only its own work. Every line that edits the data sets it back to True. The loop exits after the first pass in which no fix fired, so the final pass edits nothing and only confirms. Below, merged_into[target] reads the value stored under a key, and assigning to merged_into[account] replaces it.
merged_into = {"a": "b", "b": "c", "c": "d", "d": "d", "e": "e"}
passes = 0
changed = True
while changed:
changed = False
passes += 1
for account, target in merged_into.items():
final = merged_into[target]
if final != target:
merged_into[account] = final
changed = True
print("after pass", passes, merged_into)
print("passes:", passes)after pass 1 {'a': 'c', 'b': 'd', 'c': 'd', 'd': 'd', 'e': 'e'}
after pass 2 {'a': 'd', 'b': 'd', 'c': 'd', 'd': 'd', 'e': 'e'}
after pass 3 {'a': 'd', 'b': 'd', 'c': 'd', 'd': 'd', 'e': 'e'}
passes: 3
| After | a | b | c | d | e | Changed |
|---|---|---|---|---|---|---|
| start | b | c | d | d | e | |
| pass 1 | c | d | d | d | e | yes |
| pass 2 | d | d | d | d | e | yes |
| pass 3 | d | d | d | d | e | no |
b gets its final answer in pass 1, because its target c pointed at d from the start. The same pass moves a to c, which is closer but not final, and pass 2 finishes a. Pass 3 finds nothing to fix, and that empty pass ends the loop. Assigning to merged_into[account] during .items() is safe because it replaces a value and leaves the keys alone. The next section covers what happens when the keys change.
The pass count depends on the order of the keys. With d listed first and a last, pass 1 resolves the whole chain, because each account reads a target that was fixed earlier in the same pass. Pass 2 then confirms. The loop is correct in either order, which is its value: nobody has to work out the right order.
Putting a ceiling on the passes
A rule that undoes another rule, or data that never converges, keeps a while-changed loop running forever. A production version caps the passes with a loop else. It uses a for over pass numbers, a break when a pass changes nothing, and an else that runs only when the cap ran out without that break.
merged_into = {"a": "b", "b": "c", "c": "d", "d": "d", "e": "e"}
max_passes = 10
for pass_number in range(1, max_passes + 1):
changed = False
for account, target in merged_into.items():
final = merged_into[target]
if final != target:
merged_into[account] = final
changed = True
if not changed:
print("settled on pass", pass_number)
break
else:
print("did not settle after", max_passes, "passes")Output:
settled on pass 3
Each pass is a full walk over the data, so the work is passes times items. A cap of 10 that fires deserves an alert. It means either the data has chains longer than anyone expected, or 2 rules are fighting.
The capped loop above runs on the same 5 accounts with max_passes = 2. What does it print?
- did not settle after 2 passes: pass 2 still changed a, so no pass confirmed
- settled on pass 2: by the end of pass 2 every account points at its final target
- settled on pass 3: the else clause grants 1 extra pass when the cap is reached
- nothing at all: the else clause runs only when the loop ends through break
About this lesson
This section is part of the Loops: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.