Concepts / For Loops and Iteration in Python

For Loops and Iteration in Python

When you write a basic loop such as for item in d:, the loop gives you the dictionary's keys.

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

The Missing Half of a Dictionary Loop

A dictionary stores information as key-value pairs. When you write a basic loop such as for item in d:, the loop gives you the dictionary's keys. That is not enough when the loop body also needs each key's corresponding value. The .items() method solves this problem by providing both parts of each dictionary entry together.

What .items() Produces

The .items() method returns tuples containing a key and its value. For the dictionary d = {'a': 10, 'b': 1, 'c': 22}, calling d.items() provides the three pairs ('a', 10), ('b', 1), and ('c', 22). Each pair keeps the key connected to its corresponding value, so a loop can process both pieces during the same iteration.

a10('a', 10)b1('b', 1)c22('c', 22).items().items().items()
What does the dictionary's data look like before iteration, and what pairs does .items() provide?
python

Unpacking Each Pair

In for key, val in d.items():, the two variable names on the left match the two parts of each tuple returned by .items(). Tuple unpacking happens automatically. On each iteration, the key goes into key and the value goes into val. The variable names are chosen by the programmer; what matters is that two variables receive the two parts of each pair.

('b', 1)one .items() resultkey'b'val1first elementsecond element
How does each key-value tuple become two separate variables during a loop iteration?
Code walkthrough
for key, val in d.items():
    print(val, key)
  1. 1
    During one iteration, suppose the tuple is ('b', 1).
  2. 2
    Tuple unpacking assigns 'b' to key and 1 to val.
  3. 3
    print(val, key) therefore prints 1 followed by b.
  • The loop requests each key-value tuple from d.items().
  • The first tuple element is assigned to key.
  • The second tuple element is assigned to val.
  • The print statement uses the value first and the key second.

Tracing the Output

What do you think happens?

Predict the three output lines before reading the reveal. The loop uses d = {'a': 10, 'b': 1, 'c': 22} and print(val, key).

Reveal answer
Answer:

10 a1 b22 c

The first pair is ('a', 10), so key is 'a' and val is 10. The second pair is ('b', 1), so key is 'b' and val is 1. The third pair is ('c', 22), so key is 'c' and val is 22. Because the print statement places val before key, each line shows the value first.

('a', 10)10 a('b', 1)1 b('c', 22)22 cnext iterationnext iteration
What happens on each iteration, and what output does the loop produce?
Output
10 a
1 b
22 c
Worked example

Reading the loop one iteration at a time

Determine the values of key and val, then determine the printed line for each pair in d = {'a': 10, 'b': 1, 'c': 22}.

  1. 1
    First pair

    The tuple is ('a', 10). Unpacking assigns key = 'a' and val = 10. The statement print(val, key) produces 10 a.

  2. 2
    Second pair

    The tuple is ('b', 1). Unpacking assigns key = 'b' and val = 1. The statement print(val, key) produces 1 b.

  3. 3
    Third pair

    The tuple is ('c', 22). Unpacking assigns key = 'c' and val = 22. The statement print(val, key) produces 22 c.

Result

The output is 10 a, then 1 b, then 22 c, with one result on each line.

Choosing an Iteration Method

Python dictionaries provide .keys(), .values(), and .items() for different iteration needs. Iterating with .keys() gives the keys, iterating with .values() gives the values, and iterating with .items() gives key-value pairs. Select the method that matches the information required by the loop body.

Iteration expressionLoop variable containsUse it when
d.keys()A keyThe loop needs only keys
d.values()A valueThe loop needs only values
d.items()A key-value pairThe loop needs both keys and values

The three dictionary iteration methods differ in what information each loop iteration provides.

d.keys()keyd.values()valued.items()key and value
What does the loop receive when it iterates over keys, values, or key-value pairs?
python

Mistakes Beginners Make

  • Common mistake

    Expecting a basic dictionary loop to provide both pieces of an entry

    What it looks like
    for item in d:
    Why it fails

    A basic dictionary loop gives you only the keys, so item does not automatically contain the corresponding value.

    Do this instead

    Use for key, val in d.items(): when the loop needs both the key and its value.

  • Common mistake

    Using .keys() when the loop also needs values

    What it looks like
    for key in d.keys():
    Why it fails

    This iteration supplies keys only.

    Do this instead

    Use .items() and unpack each pair into two variables.

  • Common mistake

    Forgetting that tuple unpacking assigns two separate variables

    What it looks like
    for key, val in d.items():
    Why it fails

    The loop does not place the whole pair into one variable. It assigns the pair's first element to key and second element to val.

    Do this instead

    Trace the current tuple first, then assign its key and value to the matching variables.

  • Common mistake

    Predicting the print order from the loop header instead of the print statement

    What it looks like
    print(val, key)
    Why it fails

    The loop variables are named key and val, but the print statement places val before key.

    Do this instead

    After unpacking, read the output statement from left to right.

Practice Before Running

EASY

Predict the output of this loop before running it. Identify the tuple processed on each iteration, the values assigned to key and val, and the order in which print displays them.

scores = {'red': 8, 'blue': 3}
for key, val in scores.items():
    print(key, val)
Hints
  • Each iteration receives one key-value pair from .items().
  • The first tuple element is assigned to key and the second to val.
  • This print statement places key before val.
Worked example

Checking the prediction

For scores = {'red': 8, 'blue': 3}, determine the output of for key, val in scores.items(): print(key, val).

  1. 1
    First iteration

    The current pair is ('red', 8), so key is 'red' and val is 8. The print statement places them in the order red 8.

  2. 2
    Second iteration

    The current pair is ('blue', 3), so key is 'blue' and val is 3. The print statement places them in the order blue 3.

Result

The predicted output is red 8 followed by blue 3.

Key Takeaways

  1. 1
    The .items() method returns key-value tuples from a dictionary.
  2. 2
    The pattern for key, val in d.items(): automatically unpacks each tuple into two variables.
  3. 3
    A basic loop over a dictionary gives keys, while .keys(), .values(), and .items() let you choose keys, values, or both.
  4. 4
    To predict output, process one tuple at a time, assign its two elements, and then read the print statement in order.

At a glance

  • Use .items() when a loop needs both the key and its corresponding value.
  • Each result from .items() is a two-element tuple that Python unpacks into the variables named in the for statement.
  • Use .keys() for keys only, .values() for values only, and .items() for both.
  • Predict dictionary-loop output by tracing each key-value tuple and then following the order used by the loop body.

Related concepts

More concepts starting with F