Iteration
Iterating over Iterables
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
GuidoWhen 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 GuidoDictionaries 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 9Notes
- A
forloop consumes values from an iterable. - Different producers can feed the same loop protocol.
- Prefer
enumerate()overrange(len(...))when you need an index.
See also
- related: Iterators
- related: Iterator vs Iterable
- prerequisite: For Loops
Run the complete example
Expected output
Ada
Grace
Guido
0 Ada
1 Grace
2 Guido
Ada 10
Grace 9
Execution time appears here after you run the example.