I1 · Python Programming for AI

for Loops and range()

A for loop repeats a block of code once for each item in a sequence, such as a list, a string or a range. range(stop) produces the whole numbers from 0 up to, but not including, stop; range(start, stop, step) lets you choose where to start and how far to jump.

10 min Intermediate · Sublevel Beginner Jump to the activity

What you need: The earlier topics of this module.

Definition

How do you print the table of 7 without writing ten print lines?

A for loop repeats a block of code once for each item in a sequence, such as a list, a string or a range. range(stop) produces the whole numbers from 0 up to, but not including, stop; range(start, stop, step) lets you choose where to start and how far to jump.

In simple words

for n in range(1, 11): means 'for n = 1, 2, 3 … 10, do the indented steps'. Python sets n to each value in turn. A for loop over a list visits every item, so for name in names: greets everyone without knowing how many names there are.

Overview

  • A for loop repeats a block once for each item in a sequence or other iterable.
  • The loop variable takes each item in turn: for city in cities:.
  • range() produces a sequence of integers without storing them all, which saves memory.
  • Strings, lists, tuples, sets, dictionaries and files can all be looped over.
  • break leaves the loop early; continue skips to the next item; else runs if no break happened.
  • Loops over data are how programs process every row of a data set or every pixel of an image.

Why it matters

Computers are valuable because they repeat work tirelessly. Loops process every row of a dataset, every word in a document and every training step of a model.

Key terms

for loop
Repeats a block once for each item in an iterable.
Iterable
Anything you can loop over: a list, string, range, dictionary or file.
Loop variable
The name that takes each item's value in turn.
range()
Produces a sequence of whole numbers on demand.
Accumulator
A variable that builds up a result across iterations, such as a running total.
Nested loop
A loop inside another loop.

Types

for loops come in several common forms, depending on whether you need the items, their positions, several lists at once or every combination.

1. Looping over items

Visiting each element of a collection directly.

  • How it works: Python asks the collection for its next item until none remain, assigning each to the loop variable.
  • Example: for fruit in ["mango", "banana", "guava"]: print(fruit)
  • When to use it: Use it whenever you need each value and not its position; it is the most Pythonic form.

2. range(stop)

Counting from 0 up to, but not including, stop.

  • How it works: range(5) gives 0, 1, 2, 3, 4, so the loop runs exactly stop times.
  • Example: for i in range(3): print("Hello") prints Hello three times.
  • When to use it: Use it to repeat an action a fixed number of times, such as asking three quiz questions or drawing five stars.

3. range(start, stop, step)

Counting from start, jumping by step, and stopping before stop; the step can be negative.

  • How it works: range(2, 11, 2) gives 2, 4, 6, 8, 10; range(10, 0, -1) counts down 10 to 1.
  • Example: Printing the 7 times table: for n in range(7, 71, 7): print(n).
  • When to use it: Use it for counting with gaps, counting down, and index ranges.

4. enumerate() and zip()

enumerate() gives each item with its position; zip() walks through two or more sequences side by side.

  • How it works: enumerate(items, start=1) yields (number, item) pairs; zip(a, b) yields (a[i], b[i]) pairs and stops at the shorter list.
  • Example: for rank, name in enumerate(toppers, start=1): ... and for name, mark in zip(names, marks): ...
  • When to use it: Use them instead of range(len(...)) when you need positions or parallel lists.

5. Nested loops

A loop inside another loop, so the inner loop runs completely for each pass of the outer loop.

  • How it works: If the outer loop runs m times and the inner n times, the inner block runs m × n times.
  • Example: Printing a multiplication grid: for i in range(1, 4): for j in range(1, 4): print(i * j).
  • When to use it: Use it for grids, tables, pairs and image pixels; watch the cost, which grows quickly.

Explained in detail

Looping over things directly

Python's for loop goes through the items of a collection directly: for mark in marks: gives you each mark in turn, with no counter to manage. This is different from languages such as C, where loops count positions and you then look up each item. Looping over items directly avoids a whole family of off-by-one mistakes. You can loop over a string to get characters, over a dictionary to get keys, and over an open file to get lines, all with the same form.

The accumulator pattern

Many loops follow one pattern: set a variable to a starting value before the loop, update it inside the loop, and use it after. A total starts at 0 and adds each mark; a count starts at 0 and adds 1 when a condition is met; a maximum starts at the first item and is replaced whenever a bigger one appears; a list of results starts empty and grows with append(). Recognising this pattern makes most loop problems easy, and it is exactly how functions such as sum(), max() and len() work inside.

Helpers for loops

HelperExampleGives
range(n)for i in range(3):0, 1, 2
range(a, b, step)range(10, 0, -3)10, 7, 4, 1
enumerate()for i, name in enumerate(names, 1):Position and item together, counting from 1
zip()for n, m in zip(names, marks):Matching items from two lists
reversed()for x in reversed(items):Items from last to first
sorted()for x in sorted(items):Items in order, without changing the list

Nested loops and cost

A loop inside a loop runs the inner block once for every combination: an outer loop of 10 and an inner loop of 10 means 100 runs. Nested loops are natural for grids, tables and comparing every pair of items, but the work grows quickly. Comparing every pair among 1,000 items is about half a million comparisons; among a million items it is about half a trillion. This growth is exactly what Big-O notation, later in this module, measures.

  • Do not change a list's length while looping over it; loop over a copy, such as items[:], or build a new list.
  • range() does not build a list in memory, so range(1_000_000) costs almost nothing until used.

How it works

CallNumbers produced
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(0, 10, 2)0, 2, 4, 6, 8
range(5, 0, -1)5, 4, 3, 2, 1

enumerate() gives both the position and the item, and is handy when you need a counter.

In code

A times table with range, a loop over a list, and a running total.

times_table.py
for n in range(1, 11):
    print(7, "x", n, "=", 7 * n)

fruits = ["mango", "banana", "guava"]
for position, fruit in enumerate(fruits, start=1):
    print(position, fruit)

total = 0
for marks in [72, 85, 64]:
    total += marks
print("Total marks:", total)

Output

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
1 mango
2 banana
3 guava
Total marks: 221

Try it yourself

How many times does it run?

Match each loop header to the numbers it goes through.

  • for i in range(3):
  • for i in range(2, 5):
  • for i in range(1, 10, 3):
  • for i in range(3, 0, -1):

Put the lines in order

Arrange these lines into a program that prints the squares of 1 to 5 and then 'Done'. Indentation is shown.

  1. 1 print(n, square)
  2. 2 square = n * n
  3. 3print("Done")
  4. 4for n in range(1, 6):

Common mistakes

  • Expecting range(1, 10) to include 10.
  • Changing a list while looping over it.
  • Forgetting to indent the loop body, or indenting a line that should run after the loop.

Check yourself

Question 1

1. How many times does for i in range(5): run?

Question 2

2. What is the last number in range(2, 9, 2)?

Question 3

3. What does enumerate() add to a loop?

Summary

  • for repeats a block once for each item in a sequence.
  • range(start, stop, step) stops before stop.
  • enumerate gives positions; a running total adds as it goes.

Finished reading?

Sources: W3Schools: Python For Loops