Control Flow
For Loops
Direct iteration keeps the code focused on the values in the collection.
Source
for name in ["Ada", "Grace", "Guido"]:
print(name)Output
Ada
Grace
Guidorange(3) yields 0, 1, and 2 lazily. Use it when those integers are the thing being iterated over.
Source
for number in range(3):
print(number)Output
0
1
2enumerate() is the usual Python way to keep a counter beside each value without indexing back into the list.
Source
for index, name in enumerate(["Ada", "Grace"], start=1):
print(index, name)Output
1 Ada
2 GraceNotes
- A
forloop consumes an iterable until it is exhausted. - Reach for
whilewhen the stopping condition must be rechecked manually. iter()andnext()expose the protocol thatforuses internally.
See also
- related: While Loops
- next depth: Iterating over Iterables
- next depth: Iterators
Run the complete example
Expected output
Ada
Grace
Guido
0
1
2
1 Ada
2 Grace
Execution time appears here after you run the example.