LearnFrenzy
Sign in Take a free test

Loops · Lesson 11 of 39

for Loops and range()

4 min read Updated Nov 7, 2026 Saurabh Samir

Computers are brilliant at doing the same thing many times without getting bored. A for loop takes a collection – a list, a string, a range of numbers – and runs a block of code once for each item in it.

In this lesson

  • How a for loop walks through a collection
  • range() with one, two and three arguments
  • enumerate() for positions and zip() for pairs
  • Building totals and counts with an accumulator

Looping over a collection

fruits = ["mango", "banana", "guava"]

for fruit in fruits:
    print("I like", fruit)
print("Loop finished")

Output

I like mango
I like banana
I like guava
Loop finished

Read it as "for each fruit in fruits, do this". On every pass (an iteration) the name fruit points at the next item. When the items run out, the loop ends and Python continues with the next unindented line.

What happens on each pass

  1. Take the next itemfruit = "mango", then "banana"…
  2. Run the blockprint("I like", fruit)
  3. Any items left?Yes → go back to step 1
  4. No items leftContinue after the loop

Strings are collections of characters, so you can loop over them too:

for letter in "Py3":
    print(letter, end=" ")

Output

P y 3

Counting with range()

range() produces a sequence of whole numbers on demand. The stop value is never included.

CallNumbers produced
range(5)0, 1, 2, 3, 4
range(2, 6)2, 3, 4, 5
range(0, 20, 5)0, 5, 10, 15
range(10, 0, -3)10, 7, 4, 1

range(2, 10, 2): start 2, stop before 10, step 2

  1. 21st
  2. 42nd
  3. 63rd
  4. 84th

10 is the stop value, so it is not produced.

for n in range(1, 6):
    print(f"{n} x 7 = {n * 7}")

Output

1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
5 x 7 = 35
print(list(range(10, 0, -3)))
print(list(range(5, 2)))   # empty: you can't count up from 5 to 2

Output

[10, 7, 4, 1]
[]

Common mistake: off-by-one with range

To print 1 to 10 you need range(1, 11), not range(1, 10). The stop value is exclusive so that range(n) gives exactly n numbers.

The accumulator pattern

A very common job is to build up a result: start with an empty total, then add to it on every pass.

prices = [120, 45, 300, 80]

total = 0
count_over_100 = 0
for price in prices:
    total += price
    if price > 100:
        count_over_100 += 1

print("Total:", total)
print("Items over 100:", count_over_100)
print("Average:", total / len(prices))

Output

Total: 545
Items over 100: 2
Average: 136.25

(For a plain total, the built-in sum(prices) does the same in one call – but the pattern lets you compute anything.)

enumerate(): item and position together

Need the position as well as the item? Do not count by hand – use enumerate():

winners = ["Anil", "Bhavna", "Chetan"]

for rank, name in enumerate(winners, start=1):
    print(f"#{rank} {name}")

Output

#1 Anil
#2 Bhavna
#3 Chetan

Pythonic style

Coming from C or Java, you may write for i in range(len(winners)): print(winners[i]). It works, but for name in winners or enumerate() is cleaner and less error-prone. Interviewers notice this.

zip(): walking two lists in step

students = ["Ira", "Jay", "Kiran"]
scores = [88, 74, 93]

for student, score in zip(students, scores):
    print(f"{student:<6}{score}")

Output

Ira   88
Jay   74
Kiran 93

zip() stops at the shortest list. Pass strict=True if the lists must be the same length – Python then raises an error instead of silently dropping items.

Looping over a dictionary

stock = {"pens": 40, "notebooks": 12, "erasers": 0}

for item, qty in stock.items():
    status = "in stock" if qty else "OUT OF STOCK"
    print(f"{item}: {qty} ({status})")

Output

pens: 40 (in stock)
notebooks: 12 (in stock)
erasers: 0 (OUT OF STOCK)

Practice

Try it yourself

  1. Print the sum of all even numbers from 1 to 100.

    Show solution
    total = 0
    for n in range(2, 101, 2):
        total += n
    print(total)

    Output

    2550
  2. Count the vowels in "Programming in Python".

    Show solution
    text = "Programming in Python"
    vowels = 0
    for ch in text.lower():
        if ch in "aeiou":
            vowels += 1
    print(vowels)

    Output

    5
  3. Print a countdown from 5 to 1 followed by "Lift off!".

    Show solution
    for n in range(5, 0, -1):
        print(n)
    print("Lift off!")

    Output

    5
    4
    3
    2
    1
    Lift off!

Quick check

What does list(range(3, 12, 4)) give?

[3, 7, 11]

How do you get both the index and the item in a loop?

for i, item in enumerate(items):

What happens when zip() gets lists of different lengths?

It stops at the shortest one (unless you pass strict=True, which raises an error).

Summary

  • for item in collection: runs the block once per item.
  • range(start, stop, step) excludes stop.
  • Use enumerate() for positions, zip() for parallel lists, .items() for dictionaries.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links