Skip to content

for Loops and range()

You will repeat work over collections and number ranges with for loops.

10 min read 10 quiz questions

Looping through items

for item in collection:
    print(item)
A for loop can visit every character in a string and every item in a list.
for letter in 'cat':
    print(letter)

colors = ['red', 'blue']
for color in colors:
    print(color)

The first loop gives letter one character at a time. The second loop gives color each list item in order.

Range enumerate and zip

range(), enumerate(), and zip() give a for loop useful values.
for number in range(2, 8, 2):
    print(number)

for index, fruit in enumerate(['pear', 'plum'], start=1):
    print(index, fruit)

for name, score in zip(['Ana', 'Bo'], [9, 7]):
    print(name, score)

range(2, 8, 2) starts at 2, stops before 8, and steps by 2. enumerate() adds a position, while zip() pairs items from two collections until the shorter one ends.

Nested loops and else

Nested loops can build a pattern, and for can have an else clause.
for row in range(3):
    line = ''
    for column in range(row + 1):
        line += '*'
    print(line)
else:
    print('Pattern complete')

For each row, the inner loop adds the right number of stars to line. The else block runs after the outer loop finishes normally. It does not run if that loop ends with break.

Key points

  • A for loop visits items one at a time.
  • range(start, stop, step) excludes the stop value.
  • Use enumerate() when you also need positions.
  • Use zip() to loop over paired collections.
  • Nested loops repeat one loop inside another.

Worked example

Print the 7-times table rows for a school wall chart — one row per day of practice.

Example
for day in range(1, 4):
    print(day, "x 7 =", day * 7)

How it works, step by step

  1. range(1, 4) produces 1, 2, 3 — it stops BEFORE 4.
  2. Each pass binds day to the next number.
  3. The body computes and prints that day's row.

References & Further Reading

Related entries from PyLabs's own reference library.

  • range() (Make a sequence of evenly spaced integers.)
  • enumerate() (Pair each item with a counter.)
  • zip() (Pair items from two or more iterables.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Use range(1, 6) in a for loop to print the numbers 1 through 5, one per line.

Expected output:

1
2
3
4
5

# Write your code below
Want another challenge on this module? More coding practice

Check yourself

for Loops and range() quiz

10 questions. You get instant feedback per question, and the timer starts when you press the button.

Lesson incomplete

Not completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/5 complete
Module cheat sheet