Unlike a C-style for loop that manually manages a counter, Python's for loop always iterates directly over an iterable's items, pulling them one at a time via the iterator protocol. To loop a specific number of times, you iterate over a range object; to get both index and value, wrap the iterable in enumerate(); and to loop over two sequences in parallel, wrap them in zip(). Any object that implements the iterator protocol can be looped over.
1Understanding for Loop
Unlike a C-style for loop that manually manages a counter, Python's for loop always iterates directly over an iterable's items, pulling them one at a time via the iterator protocol. To loop a specific number of times, you iterate over a range object; to get both index and value, wrap the iterable in enumerate(); and to loop over two sequences in parallel, wrap them in zip(). Any object that implements the iterator protocol can be looped over.
Use enumerate() when you need an index inside a for loop, instead of manually incrementing a counter variable or indexing with range and len.
colors = ["red", "green", "blue"]
for color in colors:
print(color)2Practical Example
Here is a real-world application of for Loop showing how it is used in production Python code.
for i in range(1, 6):
if i % 2 == 0:
print(f"{i} is even")3Best Practices
Follow these guidelines when working with for Loop:
1. Iterate directly over the collection instead of indexing with range and len
2. Use enumerate() when both the index and the value are needed
3. Use zip() to iterate over two or more sequences together instead of indexing each one separately
Tip: Use enumerate() when you need an index inside a for loop, instead of manually incrementing a counter variable or indexing with range and len.
colors = ["red", "green", "blue"]
for color in colors:
print(color)