Iteration

Iterating over Iterables

for loops consume values from any iterable object.

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
ITERABLE[a,b,c]iter()ITERATORnext()abc
`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.