The for Loop
Loop directly over the items of any collection.
Syntax
for item in iterable:
...The for loop visits each item of a collection (a list, string, range, and more) in turn. You get each value directly — no counter to manage.
Looping a number of times
Combine for with range(n) to repeat something n times.
Example
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
for i in range(1, 4):
print('Count', i)
# Output:
# apple
# banana
# cherry
# Count 1
# Count 2
# Count 3When to use it
- A report generator loops over a list of records and writes each one as a formatted line.
- A scraper iterates over a collection of URLs and fetches each page in turn.
- A data migration script uses for with enumerate() to process each row with its index.
More examples
Iterate over a list
Iterates over each element in a list, binding it to the loop variable 'product'.
products = ['laptop', 'mouse', 'keyboard']
for product in products:
print('Item:', product)
# Output:
# Item: laptop
# Item: mouse
# Item: keyboardRange-based loop with index
Uses range(1, 6) to loop five times, using the index in a formatted message.
for i in range(1, 6):
print(f'Step {i}: processing batch {i * 10}')
# Output:
# Step 1: processing batch 10
# Step 2: processing batch 20
# ...Enumerate for index and value
Uses enumerate() to loop with both an index (starting at 1) and the item value.
tasks = ['Read', 'Write', 'Review']
for idx, task in enumerate(tasks, start=1):
print(f'{idx}. {task}')
# Output:
# 1. Read
# 2. Write
# 3. Review
Discussion