Concepts / Lists and Iteration

Lists and Iteration

Sometimes we want to loop through a set of things such as a list of words, the lines in a file, or a list of numbers. When we have a list of things to loop through, we can construct a definite loop using a for statement. We call the while statement an indefinite loop because it simply loops until some condition becomes False , whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.

  • Programming

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.

containscontainscontainsword listposition 1redposition 2blueposition 3green
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

Three Items, Three Iterations

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

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

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

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

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

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

next itemnext itemnext itemitems exhausteditem setred, blue, greenrediteration 1blueiteration 2greeniteration 3loop completeno items remain
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
iterates throughdepends onfor loopdefinitewhile loopindefiniteknown itemsone iteration per itemconditioncontinues until False
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.

Reading the Loop Structure

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

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

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

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

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

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

Mistakes Beginners Make

  • Assuming a for loop continues because a condition remains true.

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

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

  • Ignoring the iteration variable when tracing a loop.

    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.

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

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

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

    Fix: Identify the exact collection or slice that the loop receives.

  • Forgetting that two iteration variables can represent one structured item.

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

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

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

Key Takeaways

  • 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.