In this lesson, you will learn how to maintain a global "running total" or state that persists across multiple levels of nested loops to perform aggregate calculations.
When you use nested loops—for example, looping through a list of classrooms, and then looping through students inside those classrooms—it is easy to lose track of data. If you need to calculate something across the entire structure, such as the total number of students across all rooms, you need a way to pass information from the inner loop up to the outer level.
To do this, we use a shared state variable initialized outside the loops. The outer loop initializes the scope, but the variable lives long enough to survive every iteration of every inner loop.
Practical Example: The Global Counter
Imagine you have a list of store departments, each containing sales transactions. You want to calculate the total revenue for the entire company.
# State variable initialized outside both loops
total_revenue = 0
departments = [[10, 20], [50, 5], [100]]
for dept in departments:
# We can perform logic specific to this room here
for sale in dept:
# We update the shared state variable defined above
total_revenue += sale
print(f"Grand Total: {total_revenue}")
Why this works
- The Variable Scope: By defining
total_revenue = 0before the loops start, the variable remains accessible to the inner loop. - Persistence: Because the variable is outside the
for sale in deptblock, it does not get reset to zero every time you move to a new department. - Coordination: The inner loop acts as an "accumulator," continuously pushing values into the shared variable. Even when the inner loop finishes and the outer loop moves to the next
dept, thetotal_revenuekeeps its value, ensuring the final result is a true aggregate of all levels.
When you need to keep track of a count, a sum, or even a specific flag across deep nesting, always place your state variable at the level where that information is needed.
Key Takeaway: Initialize your tracker variables outside the nested structure to ensure your state persists across every iteration of your loops.