The for Loop

Loop directly over the items of any collection.

Syntaxfor 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.

A for loop taking one item at a time from an iterable102030iterable (list)one itemeach passfor item in ...:print(item)the loop body runs once for every item
A for loop pulls one item at a time from the iterable and runs its body for each.

Example

Example · python
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 3

When 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'.

Example · python
products = ['laptop', 'mouse', 'keyboard']
for product in products:
    print('Item:', product)

# Output:
# Item: laptop
# Item: mouse
# Item: keyboard

Range-based loop with index

Uses range(1, 6) to loop five times, using the index in a formatted message.

Example · python
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.

Example · python
tasks = ['Read', 'Write', 'Review']
for idx, task in enumerate(tasks, start=1):
    print(f'{idx}. {task}')

# Output:
# 1. Read
# 2. Write
# 3. Review

Discussion

  • Be the first to comment on this lesson.