Iteration

Iterating over Iterables

for loops consume values from any iterable object.

Python's for statement consumes values from any iterable object: lists, strings, dictionaries, ranges, generators, files, and many standard-library helpers.

This makes iteration a value-stream protocol rather than a special case for arrays. The producer decides how values are made, and the loop consumes them one at a time.

Use enumerate() when you need positions and values together, and dict.items() when you need keys and values. These helpers express intent better than manual indexing.

Start with an ordinary list. A list stores values, and a for loop asks it for one value at a time.

When you only need the values, iterate over the collection directly. There is no index variable because the loop body does not need one.

Source

names = ["Ada", "Grace", "Guido"]

for name in names:
    print(name)

Output

Ada
Grace
Guido
for desugars to iter()+next(): one iter() call, then next() until StopIteration ends the loop.

When you need both a position and a value, use enumerate(). It produces index/value pairs without manual indexing.

Source

for index, name in enumerate(names):
    print(index, name)

Output

0 Ada
1 Grace
2 Guido

Dictionaries are iterable too, but dict.items() is the clearest way to say that the loop needs keys and values together.

Source

scores = {"Ada": 10, "Grace": 9}
for name, score in scores.items():
    print(name, score)

Output

Ada 10
Grace 9

Notes

See also

Run the complete example

Example code

Expected output

Ada
Grace
Guido
0 Ada
1 Grace
2 Guido
Ada 10
Grace 9

Execution time appears here after you run the example.