Concepts / Modifying Lists During Iteration

Modifying Lists During Iteration

For loops are the most common and natural way to iterate through list elements, using identical syntax to string iteration.

  • Programming

One Element at a Time

When a list contains several items, a for loop provides a natural way to visit each item in turn. The loop assigns one list element to the loop variable for each iteration, then continues through the list. This is different from manually asking for one element at a time by index.

The loop variable contains the actual element value, not the element's index.

Following the List Positions

Imagine the loop moving from the first position of the list to the next position, visiting each position in order. At every position, the loop variable receives the value stored there. The loop body then works with that value. If the list has three elements, the loop body receives three element values, one per iteration.

first iterationsecond iterationthird iterationposition 0reditemredposition 1greenitemgreenposition 2blueitemblue
How does the loop move from one list position to the next, and which element is assigned to the loop variable at each step?

A loop variable is the name that receives the current list element during an iteration. It is not automatically the numeric position of that element.

Reading Each Element

The syntax for iterating over a list uses the same general form as iteration over a string: choose a loop variable, provide the list, and place the work to perform inside the loop body. For a list of items, the loop variable receives the first item, then the second item, and so on until the elements have been visited.

python
Output
red
green
blue

The first iteration assigns red to color, the second assigns green, and the third assigns blue. The loop variable therefore gives the loop body the values themselves. If the positions are needed instead, the source pack identifies range(len(list)) as the alternative approach.

Nested Lists Stay Whole

A nested list is still one element of its outer list. When a for loop iterates over the outer list, it visits the nested list as a whole rather than automatically visiting the values inside that nested list.

containscontainscontainsone outer iterationouter listfirst item, inner list,third itemfirst iteminner listtwo valuesloop variableinner listthird item
When a for loop iterates over an outer list, does it visit the inner list's individual values or treat the entire inner list as one element?

For example, if an outer list contains an inner list, the outer loop has one iteration in which the loop variable holds that inner list. The inner values are not separate outer-loop iterations.

When the List Is Empty

An empty list contains no elements to visit. Consequently, the loop body runs zero times. This is expected behavior, not an error: the loop receives a valid list, but there is no element to assign to the loop variable.

begin iterationno elementempty listno elementsfind next elementnone availableloop endsbody runs zero times
What path does control flow take when a for loop receives an empty list, and why does the loop body run zero times?
python
Output
No output

What Modification Means Here

The source material establishes how a for loop traverses list elements, including empty and nested lists. It does not specify the detailed behavior of adding, removing, or changing list elements while that traversal is in progress. Therefore, do not use the traversal rules alone to predict every result of mutating a list during a loop. First separate the question of which elements the loop visits from the separate question of how a particular modification affects an ongoing iteration.

during iterationduring iterationduring iterationrequires additional rulesrequires additional rulesrequires additional ruleslistbeing traversedaddmodificationoutcomenot specified hereremovemodificationchangemodification
What happens to the list and the next iteration when an element is added, removed, or changed while the for loop is running? The provided material defines the traversal model but does not define those modification outcomes.

Predict Before Running

What do you think happens?

What values reach the loop body, in order, when the outer list contains a word, a nested list, and another word?

  • The word, each value inside the nested list, then the final word
  • The word, the entire nested list, then the final word
  • Only the values inside the nested list
  • No values, because nested lists cannot be iterated over
Reveal answer

Answer: The word, the entire nested list, then the final word

The loop is iterating over the outer list. The nested list is one element of that outer list, so it reaches the loop body as one whole element.

python
Output
A
['B', 'C']
D
EASY

Before running a for loop, write down the outer list's elements in order. Mark each element as one item, even when that item is itself a list. Then write the value assigned to the loop variable on each iteration.

Hints
  • Count elements in the outer list, not values inside a nested element.
  • The loop variable receives an element value rather than an index.
  • An empty outer list gives you no loop-body values to write down.

Common Prediction Errors

  • Treating the loop variable as an index

    The loop variable holds the actual element value on each iteration.

    Fix: Use the element value directly. If an index is needed, use the range(len(list)) approach identified in the source material.

  • Expecting the loop body to run once for an empty list

    An empty list has no element to assign to the loop variable.

    Fix: Predict zero loop-body executions.

  • Flattening a nested list mentally

    Nested lists are treated as single elements during iteration over the outer list.

    Fix: Count the nested list once at the outer level.

  • Assuming the basic traversal rule completely explains mutation

    The provided material does not define the detailed effects of list modification during an ongoing iteration.

    Fix: Separate the established traversal facts from mutation-specific rules that must be learned separately.

Iteration Checklist

first iterationnext iterationcontinueno more elementslistordered elementsfirst elementloop variablesecond elementloop variablenext elementcontinues in orderloop endsafter elements are visited
In what order does each list element reach the loop body, and what output is produced at each iteration before the loop ends?
  1. A for loop is a natural way to traverse the elements of a list.
  2. The loop variable receives each element value, not its index.
  3. An empty list causes the loop body to execute zero times.
  4. A nested list is one element of its outer list during outer-list iteration.
  5. To predict output, list the outer elements in order and assign each one to the loop variable in turn.

Key Takeaways

  • For loops visit list elements in order and provide each element to the loop body.
  • The loop variable stores an element value rather than an index.
  • An empty list produces no loop-body executions.
  • A nested list counts as one element when iterating over its outer list.
  • The provided material establishes traversal behavior but does not define the detailed effects of modifying a list during an ongoing iteration.