Concepts / Iterating Over Lists and Other Sequences

Iterating Over Lists and Other Sequences

In Python, the loop variable normally represents the current value supplied by the sequence, not a position that you must manually increase.

  • 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 Different Kind of For Loop

If you learned to program with C or C++, the word for may suggest a counter, a condition, and an update operation. Python uses the same keyword for a different mechanism. Its for loop is iterator-based rather than index-based: Python obtains values from a sequence one at a time and assigns each value to the loop variable.

Key point

In Python, the loop variable normally represents the current value supplied by the sequence, not a position that you must manually increase.

Values Moving Through the Loop

Sequencevalues in orderFirst valueloop variableNext valueloop variableLast valueloop variableLoop bodyruns once per valuesuppliesthen suppliesfinally suppliesruns withruns withruns with
How does control and data move from a Python sequence into the loop variable on each iteration?

An iterator is an object that knows how to produce values one at a time and in order. For a Python for loop, Python creates an iterator from the object after in. It repeatedly asks that iterator for the next value, assigns the value to the loop variable, runs the loop body, and then requests another value. When no values remain, the loop stops.

Worked example

Following Five Values

What values does the loop variable receive in for i in range(0, 5)?

  1. 1
    Start

    Python creates an iterator from range(0, 5).

  2. 2
    First iterations

    The iterator supplies 0, then 1, then 2. Each supplied value is assigned to i before the loop body runs.

  3. 3
    Final iterations

    The iterator supplies 3 and then 4. After those values have been used, there are no more values.

Result

The loop variable receives 0, 1, 2, 3, and 4, one value per iteration.

Counting Versus Iterating

C or C++ loopindex-basedPython for loopiterator-basedDeclare imanualSequence valuesautomatic sourceInitialize imanualAssign current valueautomaticCheck conditionmanualStop at endautomaticIncrement imanualrequiresthenthenafter bodyreadssuppliescontinues until exhausted
What steps must a programmer manage in a C or C++ loop compared with the automatic value iteration performed by Python?

A C or C++ loop such as for (int i = 0; i < 5; i++) makes three responsibilities explicit: initialize the counter, check the condition before each iteration, and increment the counter after each iteration. In Python, for i in range(0, 5) expresses the values to use and leaves those three management tasks to Python.

Translating the Loop

C or C++ loopfor (int i = 0; i < 5; i++)Python loopfor i in range(0, 5)icounter0, 1, 2, 3, 4iterator valuesThree manual tasksinitialize, check,incrementLoop managementautomaticusesrequiresreceiveshandles
How does a C or C++ loop using a counter map to a Python loop that receives each value directly?
cpp
python
Worked example

A Direct Translation

Translate a C or C++ loop that repeats five times into Python.

  1. 1
    Identify the counter range

    The C or C++ condition i < 5, starting from 0 and increasing by 1, produces the values 0 through 4.

  2. 2
    Use range

    Python expresses those values with range(0, 5).

  3. 3
    Write the Python loop

    Place the loop body after for i in range(0, 5):. Python supplies each value and manages the stopping condition and progression.

Result

for i in range(0, 5): is the Python equivalent of the stated C or C++ counting loop.

Lists and Other Iterables

The same iterator-based idea applies beyond a numeric range. Python can iterate over lists, tuples, strings, dictionaries, sets, and custom objects. The loop does not need to know the sequence length or manually manage an index; it requests values from the iterable until no values remain.

python
Output
red
green
blue

Here, item receives each element of the list in order. It is not a counter containing 0, 1, and 2. The loop body runs once with red, once with green, and once with blue. This direct relationship between the loop variable and the current element is what makes the loop useful for many kinds of sequences.

The Foreach Connection

LanguageLoop styleWhat the loop variable receives
Pythonfor item in sequenceThe next value from the iterable
C#foreach loopEach element from the sequence
Javaenhanced for loopEach element from the sequence
C or C++Index-based for loopA manually managed counter value

Python's for loop is closer in behavior to C# foreach and Java enhanced-for than to the traditional C or C++ counting loop.

C# programmers may recognize Python's loop as similar to foreach. Java programmers may recognize it as similar to the enhanced for loop introduced in Java 1.5. In all three styles, the loop works through a sequence and automatically delivers each element to the loop variable, without requiring manual index or counter management.

Mistakes Beginners Make

  • Common mistake

    Treating the Python loop variable as a manually managed index.

    What it looks like
    for item in items: assumes item is a position such as 0 or 1.
    Why it fails

    The iterator supplies the current value from the sequence, not a counter that you increment yourself.

    Do this instead

    Use the loop variable as the current element unless the task specifically requires a position.

  • Common mistake

    Manually adding initialization, a stopping condition, or an increment to a Python for loop.

    What it looks like

    Trying to reproduce the three control expressions from a C or C++ for statement.

    Why it fails

    Python's iterator-based loop already obtains values and stops when the iterator has no more values.

    Do this instead

    Name the loop variable and the iterable directly, such as for item in items:.

  • Common mistake

    Assuming every Python for loop must use an index.

    What it looks like

    Using a counter when the loop only needs to process each list element.

    Why it fails

    Python can iterate directly over lists and other sequences without knowing their length or managing positions.

    Do this instead

    Iterate over the sequence itself when the body needs the elements.

  • Common mistake

    Forgetting that index-based loops can create management bugs.

    What it looks like

    A manually controlled loop uses the wrong boundary or fails to advance its counter.

    Why it fails

    Such mistakes can produce off-by-one errors or infinite loops.

    Do this instead

    Prefer Python's iterator-based form when direct value iteration expresses the task.

Practice the Translation

EASY

Explain how you would translate a C or C++ loop that initializes i to 0, continues while i is less than 5, and increments i after every iteration. Then describe what the Python loop variable receives on each iteration.

Hints
  • Identify the values produced by the C or C++ loop.
  • Use Python's range form to express those values.
  • Remember that Python supplies each value to the loop variable automatically.
MEDIUM

A list contains three colors. Describe why a Python loop written as for color in colors: is more direct than a C or C++ loop that manually uses a counter to reach each element.

Hints
  • Ask what the loop body actually needs: a position or the color itself.
  • Compare direct element delivery with manual counter management.

Key Takeaways

  1. 1
    Python's for loop is iterator-based: it receives values from a sequence one at a time.
  2. 2
    A traditional C or C++ for loop is index-based and requires manual initialization, condition checking, and incrementing.
  3. 3
    for i in range(0, 5) produces 0, 1, 2, 3, and 4 without manually managing a counter.
  4. 4
    Python's loop is similar in behavior to C# foreach and Java enhanced-for loops.
  5. 5
    Direct iteration reduces opportunities for off-by-one errors, infinite loops, and forgotten increments.

At a glance

  • Python for loops obtain values from iterators instead of requiring a manually controlled index.
  • The loop variable receives the current element or value supplied by the iterable.
  • Traditional C and C++ loops expose counter management; Python hides that control for direct value iteration.
  • Python's approach resembles C# foreach and Java enhanced-for loops.
  • Removing manual initialization, boundary checks, and increments makes iteration simpler and less error-prone.

Related concepts

More concepts starting with I