Concepts / Lists and Iteration

Lists and Iteration

Iteration is the process of moving through those items one at a time.

  • Programming
Interactive lab

Try it: What a for Loop Hands You

What a Python for loop gives its loop variable from each kind of iterable: the characters of a string, the positions from range(len(word)), the elements of a list, (index, item) pairs from enumerate(), the numbers of range(start, stop, step), a dict's keys, its .values() and its .items() tuples unpacked into key, val, the inner lists of a nested list and the values an inner loop visits; and why removing items from a list while looping over it skips the next item, while looping over a copy nums[:] does not.

How it works

  1. The for statement asks the object for an iterator, then calls next() on it once per pass.
  2. Each next() result is bound to the loop variable (a tuple result such as ('a', 10) or (0, 'red') is unpacked into two names), and the indented body runs once with it.
  3. A string gives characters, a list gives element values (not positions), range() computes start, start + step, … stopping before stop, and a dict gives its keys in insertion order (.values() the values, .items() key-value tuples).
  4. A nested list's inner list is one element of the outer loop; a second, inner for loop is needed to visit the values inside it.
  5. A list iterator only remembers a position number into the live list: removing an item shifts the later items left, so the item that slides into the passed position is skipped. Looping over a copy (nums[:]) keeps the positions fixed.
  6. When next() has nothing left the loop ends (StopIteration) and the loop variable keeps its last value; an empty iterable runs the body zero times.

Default run (10 steps): A 3-line program. Step through it: each pass of the for loop asks the iterator for its next item, binds the loop variable to it and runs the indented body once. … Done: the loop body ran 3 times. Output: red | green | blue.

Simplified: The programs are twelve fixed templates: you choose the loop and edit only its data (a short string, list items that are words or integers, key: value pairs with word keys and integer values, range numbers from -20 to 20, up to 4 rows of integers, up to 10 numbers). Nothing you type is executed: the lab's own small parsers turn it into literals, and a model of CPython's iterator protocol written for these loops runs the program. Every program was also run in CPython 3.12 under sys.settrace, and the lab reproduces the variables before every line, the printed output, the final variables and the error.

Educational simulation

Loading the simulation…

A List as a Set of Work

Many programming tasks involve doing the same kind of work for several things: a list of words, the lines in a file, or a list of numbers. Iteration is the process of moving through those items one at a time. When the items are already collected in a list, a for statement provides a direct way to process the known set.

word listposition 1redposition 2blueposition 3greencontainscontainscontains
What does the list contain, and how does each item correspond to its position in the sequence?

The diagram uses a three-item word list as a teaching example. The important idea is that the list supplies a known collection of items, and the loop can visit those items in sequence. The loop does not need a separate instruction for each word; the for statement makes the repeated visits part of the loop.

Tracing Each Visit

Worked example

Three Items, Three Iterations

Imagine a for loop processing the generated list containing red, blue, and green.

  1. 1
    First visit

    The iteration variable receives the first item, red, and the loop body runs once.

  2. 2
    Second visit

    The iteration variable receives the second item, blue, and the loop body runs again.

  3. 3
    Third visit

    The iteration variable receives the third item, green, and the loop body runs for the third time.

  4. 4
    Completion

    There are no more items in the known set, so the loop has completed its three iterations.

Result

The loop body runs once for each item in the list.

item setred, blue, greenrediteration 1blueiteration 2greeniteration 3loop completeno items remainnext itemnext itemnext itemitems exhausted
What happens next as a for loop visits each item, and when does the loop stop?

A for loop has an iteration variable. On each iteration, that variable represents the current value from the list. The loop body is executed once for each value. Even when the loop body does not use the iteration variable, the variable still controls the repeated execution by moving through the values in the list.

What do you think happens?

A list contains five items. How many times does a for loop run through that list?

  • Once

  • Four times

  • Five times

  • Until an unrelated condition becomes False

Reveal answer
Answer:

Five times

A for loop processes a known set of items, so it runs through as many iterations as there are items in that set.

Definite and Indefinite Loops

Loop kindWhat controls repetitionHow completion is described
for loopA known set of itemsRuns once for each item in the set
while loopA conditionContinues until the condition becomes False

The distinction between definite and indefinite loops

for loopdefinitewhile loopindefiniteknown itemsone iteration per itemconditioncontinues until Falseiterates throughdepends on
What is the difference between looping through a known set of items and looping until a condition becomes false?

The word definite refers to the known set of items that determines the number of for-loop iterations. If the set contains a particular number of items, the loop runs that many times. A while statement is called an indefinite loop because its repetition is described through a condition: it continues looping until that condition becomes False.

Iteration Beyond Simple Values

Iteration can also work with more structured collections. The source describes items returning a list of tuples. In that situation, key and val act as two iteration variables through tuple assignment, and each pass handles one key-value pair from the dictionary.

The same idea applies when a loop processes only part of a list. The source describes iterating through a slice written as lst[:10] to print the ten most common words. The loop still follows the same definite-loop principle: it processes the items supplied by the collection being iterated over.

Worked example

Reading the Loop Structure

A loop iterates through a collection of key-value pairs using two iteration variables.

  1. 1
    Collection

    The collection supplies a list of tuples, with each tuple representing a key-value pair.

  2. 2
    Assignment

    The two iteration variables, key and val, receive the two parts of the current tuple.

  3. 3
    Progression

    The loop moves to the next key-value pair and assigns its two parts to key and val.

  4. 4
    Completion

    The loop finishes after the available key-value pairs have been processed.

Result

Multiple assignment lets one iteration step handle both parts of each tuple.

Mistakes Beginners Make

  • Common mistake

    Assuming a for loop continues because a condition remains true.

    What it looks like

    Treating a for loop as if it were an indefinite while loop.

    Why it fails

    A for loop is controlled by the known set of items and runs once for each item in that set.

    Do this instead

    Ask how many items are available to the loop, then expect one iteration for each item.

  • Common mistake

    Ignoring the iteration variable when tracing a loop.

    What it looks like

    Thinking the loop body runs repeatedly without tracking which list value controls each pass.

    Why it fails

    The iteration variable controls the loop and causes the loop body to execute once for each value in the list, even if the body does not use the variable.

    Do this instead

    Write down the current item at every iteration, including when the loop body does not use it.

  • Common mistake

    Expecting a loop over a partial list to process the entire original list.

    What it looks like

    Confusing iteration through lst[:10] with iteration through all of lst.

    Why it fails

    The described loop iterates through the slice supplied to it, which is used to print the ten most common words.

    Do this instead

    Identify the exact collection or slice that the loop receives.

  • Common mistake

    Forgetting that two iteration variables can represent one structured item.

    What it looks like

    Treating key and val as unrelated loop counters.

    Why it fails

    They are assigned from the two parts of each tuple returned by items.

    Do this instead

    Trace the tuple assignment as one key-value pair per iteration.

Best practice

When tracing any loop, identify three things before predicting its behavior: the collection or condition controlling repetition, the iteration variable or variables, and the event that ends the loop. For a for loop, the ending event is reaching the end of the known set. For a while loop, the ending event is the condition becoming False.

Practice the Trace

EASY

A generated list contains four numbers. Describe the sequence of events in a for loop that processes the list. State how many times the loop body runs, what the iteration variable represents on each pass, and what causes the loop to stop.

Hints
  • The loop body runs once for each item in the known set.
  • Track the current list value as the iteration variable.
  • The loop stops after there are no more items to process.
MEDIUM

Compare these two descriptions: processing every item in a known list, and repeating until a condition becomes False. Identify which description matches a for statement and which matches a while statement. Explain why.

Hints
  • Look for whether repetition is controlled by a known collection or by a condition.
  • A definite loop has a known set of items.
  • An indefinite loop continues until its condition becomes False.

Key Takeaways

  1. 1
    A list provides a set of items that a loop can process one at a time.
  2. 2
    A for loop is definite because it runs once for each item in a known set.
  3. 3
    The iteration variable represents the current item and controls each execution of the loop body.
  4. 4
    A while loop is indefinite because it continues until its condition becomes False.
  5. 5
    When tracing a loop, track the collection, the iteration variable, and the event that ends repetition.

At a glance

  • Lists hold sets of items that can be processed through iteration.
  • A for loop visits each item in a known set, so its number of iterations is determined by that set.
  • The iteration variable tracks the current value during each pass.
  • A while loop differs because it continues until a condition becomes False.
  • Structured items, such as key-value tuples or list slices, can also be the collection supplied to a for loop.

Related concepts

More concepts starting with L