Skip to content
Python

Python for Loops and range(): Lists, Strings and enumerate()

Ihsan Ullah · Updated · 10 min read
Python course Lesson 12 cover: Python for loop with range(), enumerate() and nested loops

Python course · Module 3: Control flow · Lesson 12 of 63

Quick answer: A Python for loop repeats a block of code once for each item in a collection, such as a list or a string: for product in products: gives product the next item on every pass. To repeat something a set number of times, loop over range(): range(5) gives 0, 1, 2, 3, 4, and range(start, stop, step) lets you choose where to start, where to stop (the stop value itself is never included) and how big each step is. Use enumerate() when you also need each item’s position.

In this lesson you will learn:

  • how a for loop walks through a list or a string, item by item
  • how to add up values with a running total
  • how range(stop), range(start, stop) and range(start, stop, step) work
  • how to number items with enumerate() and how nested loops run
  • what the else part of a for loop does

Before you start: finish Lesson 11, Python if, elif and else Statements (and match), because the loops here use if inside them. You will also use print(..., end=" ") from Lesson 10 and f-strings from Lesson 7. All examples were tested on Python 3.14.6 and behave the same on Python 3.15.2, the newest release on python.org.

Your first for loop

Our online shop has four products, and we want to print a line for each one. A list keeps several values in one variable, in square brackets and separated by commas. Lesson 15 covers lists fully; for now, you only need to know that a for loop can walk through one.

products = ["Notebook", "Pen", "Backpack", "Water bottle"]
for product in products:
    print("In stock:", product)
print("Checked", len(products), "products.")
In stock: Notebook
In stock: Pen
In stock: Backpack
In stock: Water bottle
Checked 4 products.

How it works:

  • for product in products: takes the first item, stores it in the loop variable product, and runs the indented block. Then it takes the next item, and so on until the list ends. Each run of the block is called an iteration.
  • The block follows the same rules as an if block: a colon at the end of the line and 4 spaces of indentation.
  • The last line is not indented, so it runs once, after the loop has finished.

The Python tutorial puts it this way: Python’s for statement “iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence”. You choose the loop variable’s name; a singular name for the item and a plural name for the list (product, products) reads well.

Looping over a string

A string is a sequence of characters, so a for loop gives you one character at a time.

code = "EID2026"
for character in code:
    print(character, end=" ")
print()

digits = 0
for character in code:
    if character in "0123456789":
        digits += 1
print("Digits in the code:", digits)
E I D 2 0 2 6 
Digits in the code: 4

end=" " keeps all the characters on one line, and the empty print() ends that line. The second loop combines a loop with an if: for each character, in (from Lesson 9) checks whether it is a digit, and digits += 1 counts it. A variable like digits that starts at 0 and grows inside a loop is called a counter.

A running total

The same idea adds up numbers. Start a variable at 0 before the loop and add to it inside the loop.

prices = [450, 1200, 85.5, 300]
total = 0
for price in prices:
    total += price
    print(f"Added {price}, total is now {total}")
print(f"Cart total: {total:,.2f}")
Added 450, total is now 450
Added 1200, total is now 1650
Added 85.5, total is now 1735.5
Added 300, total is now 2035.5
Cart total: 2,035.50

The print() inside the loop shows the total after each step, a good way to see what a loop is doing. The final line is outside the loop, so it prints once. (The total becomes a float after 85.5 is added, as you saw in Lesson 6.)

The range() function

To repeat something a number of times, or to loop over numbers, use range(). It can take one, two or three whole numbers:

CallNumbers it givesMeaning
range(5)0 1 2 3 4from 0 up to, but not including, 5
range(1, 6)1 2 3 4 5from 1 up to, but not including, 6
range(0, 21, 5)0 5 10 15 20count up in steps of 5
range(10, 0, -2)10 8 6 4 2count down in steps of 2

Here is the real output:

for number in range(5):
    print(number, end=" ")
print()

for number in range(1, 6):
    print(number, end=" ")
print()

for number in range(0, 21, 5):
    print(number, end=" ")
print()

for number in range(10, 0, -2):
    print(number, end=" ")
print()

print(list(range(1, 6)))
print(list(range(5, 1)))
0 1 2 3 4 
1 2 3 4 5 
0 5 10 15 20 
10 8 6 4 2 
[1, 2, 3, 4, 5]
[]

The rules to remember:

  • The stop number is never included. The tutorial says “The given end point is never part of the generated sequence”. So range(5) gives five numbers, 0 to 4, and to count from 1 to 5 you write range(1, 6).
  • start is 0 and step is 1 when you leave them out.
  • A negative step counts down. Then the stop must be smaller than the start.
  • list(range(...)) shows all the numbers at once. range(5, 1) is empty, because you cannot count up from 5 to 1, so a loop over it does not run.

range() does not build a long list in memory. The Built-in Types page explains that it stores only the start, stop and step values, so range(1_000_000) is as small as range(5).

Example: a times table

n = 7
for i in range(1, 11):
    print(f"{n} x {i:>2} = {n * i:>2}")
7 x  1 =  7
7 x  2 = 14
7 x  3 = 21
7 x  4 = 28
7 x  5 = 35
7 x  6 = 42
7 x  7 = 49
7 x  8 = 56
7 x  9 = 63
7 x 10 = 70

range(1, 11) gives 1 to 10. The format spec :>2 from Lesson 7 makes each number two characters wide, so the columns line up.

The loop variable after the loop

The loop variable is a normal variable. It keeps its last value after the loop ends:

for count in range(3):
    print("Inside the loop, count =", count)
print("After the loop, count =", count)
Inside the loop, count = 0
Inside the loop, count = 1
Inside the loop, count = 2
After the loop, count = 2

The language reference confirms that names in the loop “are not deleted when the loop is finished”. Do not rely on this too much, though: if the list is empty, the loop never runs and the variable is never created.

enumerate(): items with their position

Often you want each item and its number, for example to print a numbered menu. enumerate() gives both at once:

products = ["Notebook", "Pen", "Backpack"]

for index, product in enumerate(products):
    print(index, product)

for number, product in enumerate(products, start=1):
    print(f"{number}. {product}")
0 Notebook
1 Pen
2 Backpack
1. Notebook
2. Pen
3. Backpack

On each pass, enumerate() gives a pair: a count and the item. Writing two names, for index, product in ..., puts the count in the first and the item in the second, just like a, b = 1, 2 in Lesson 5. The count starts at 0, like string indexes; start=1 makes it start at 1, which is better for lists that people read.

Nested loops

A loop can sit inside another loop. The inner loop runs completely for every single pass of the outer loop.

sizes = ["S", "M", "L"]
colours = ["red", "blue"]
for size in sizes:
    for colour in colours:
        print(f"T-shirt, size {size}, {colour}")
print("Total:", len(sizes) * len(colours), "versions")
T-shirt, size S, red
T-shirt, size S, blue
T-shirt, size M, red
T-shirt, size M, blue
T-shirt, size L, red
T-shirt, size L, blue
Total: 6 versions

The outer loop picks S, the inner loop prints both colours, and only then does the outer loop move on to M. Three sizes times two colours gives six lines. Nested loops with range() are a classic way to print a grid:

for row in range(1, 4):
    for col in range(1, 6):
        print(f"{row * col:4}", end="")
    print()
   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15

The inner print() uses end="" to stay on the same line. The empty print() belongs to the outer loop (look at its indentation), so it ends the line after each row.

for … else, briefly

A for loop can have an else block. It runs only if the loop finished without being stopped by break. break stops a loop at once; you will learn it fully in Lesson 13. Together they are handy for searching:

products = ["Notebook", "Pen", "Backpack"]

wanted = "Pen"
for product in products:
    if product == wanted:
        print(wanted, "found!")
        break
else:
    print(wanted, "is not in the shop.")

wanted = "Laptop"
for product in products:
    if product == wanted:
        print(wanted, "found!")
        break
else:
    print(wanted, "is not in the shop.")
Pen found!
Laptop is not in the shop.

Look closely at the indentation: the else lines up with for, not with if. The tutorial says the same: “the else clause belongs to the for loop, not the if statement”. For "Laptop" the loop checked every product, never hit break, so the else block ran.

Try it yourself

Exercise 1: Even numbers

Print the even numbers from 2 to 20 on one line, using range() with a step.

Exercise 2: Add up 1 to 100

Use a for loop and range() to add up all whole numbers from 1 to 100, and print the result.

Exercise 3: Count the vowels

Count how many vowels (a, e, i, o, u) are in the word "programming".

Solutions

Solution 1

for number in range(2, 21, 2):
    print(number, end=" ")
print()
2 4 6 8 10 12 14 16 18 20 

The stop is 21, not 20, because the stop number is never included.

Solution 2

total = 0
for number in range(1, 101):
    total += number
print("Sum of 1 to 100:", total)
Sum of 1 to 100: 5050

range(1, 101) gives 1 to 100, and the running total adds each one.

Solution 3

word = "programming"
vowels = 0
for letter in word:
    if letter in "aeiou":
        vowels += 1
print(f"'{word}' has {vowels} vowels.")
'programming' has 3 vowels.

The loop checks each letter, and the counter grows for o, a and i.

Common mistakes

  • Looping over a number. for i in items: where items = 5 gives TypeError: 'int' object is not iterable. A number is not a collection; write for i in range(items):.
  • Giving range() a float. boxes = 10 / 2 makes 5.0, and range(boxes) gives TypeError: 'float' object cannot be interpreted as an integer. Use // or int() to get a whole number.
  • Expecting the stop number. range(1, 10) stops at 9. Add 1 to the stop when you want it included. A step of 0 gives ValueError: range() arg 3 must not be zero.
  • Indenting the final print by mistake. If print("Cart total:", total) is indented under the loop, it prints after every item (450, 1650, 1950) instead of once. Check which lines belong inside the loop.
  • Forgetting the colon. for product in ["Pen", "Notebook"] without : gives SyntaxError: expected ':'.

Frequently asked questions

How does range() work in a Python for loop?

range(stop) counts from 0 up to stop - 1, range(start, stop) counts from start up to stop - 1, and a third number sets the step, which can be negative to count down. The for loop takes the numbers one at a time. Use list(range(...)) to see the numbers.

How do I get the index in a Python for loop?

Use enumerate(): for index, item in enumerate(items):. It gives a count and the item on every pass, starting at 0, or at any number you pass with start=. The tutorial’s Looping Techniques section shows this use of enumerate().

When should I use a for loop instead of a while loop?

Use for when you know what to loop over: a list, a string or a fixed range(). Use while when the loop should continue until something happens, such as the user typing a correct answer. Lesson 13 covers while loops.

Summary

  • for item in collection: runs the indented block once for each item in a list or string, in order.
  • A counter or running total starts before the loop and changes inside it.
  • range(start, stop, step) gives whole numbers from start up to, but not including, stop; a negative step counts down.
  • enumerate() gives each item with its position; start=1 numbers from 1.
  • In nested loops the inner loop runs fully for each outer pass; a for loop’s else runs only when no break happened.

Next lesson

Next: Lesson 13, Python while Loops, break and continue: Infinite Loops and Input Checks.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *