CodeBlanks Logo Icon CodeBlanks

The for loop

Learn to iterate over iterables with for.

The for loop

A for loop repeats a block for each item of a collection (list, string, range):

for letter in "abc":
    print(letter)

This prints 'a', 'b', 'c' on separate lines. The in keyword specifies the collection. The loop variable (letter) takes each item in turn.

The for loop ends when the collection is exhausted. This structure is the basic tool for repetitive tasks.

Looping over strings and lists

The for loop works on ordered collections like strings and lists. Each character of a string, each item of a list is a step:

for item in [10, 20, 30]:
    print(item)

for char in "Hello":
    print(char)

You choose the loop variable name (item, char); a meaningful name makes code readable.

Practice Loop over a list

Assign numbers = [10, 20, 30]. Write for n in numbers: print(n).

Starter code

main.py
# for loop

Sample solution

main.py
numbers = [10, 20, 30]
for n in numbers:
    print(n)

Expected output

10
20
30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many times does for x in [1, 2, 3]: print(x) run?

  • 3 Correct answer
  • 2
  • 1
  • 0

Explanation: The list has 3 items, so it runs 3 times.

2 Complete the for loop

Question
for letter ____ "abc":
    print(letter)
Answer
for letter in "abc":
    print(letter)

Explanation: in specifies the collection.

3 Match the for concepts

Term Meaning
for Loop
in Collection
item Loop variable
: Opening a block

All lessons in Beginner