Learning LibraryCore Coding LibraryKids

range(): make a list of numbers to count through

range() makes a run of numbers for you to count through — 0, 1, 2, 3... — without typing them out. Loops use it to know how many times to go.

The big idea

range(n) makes the numbers 0 up to (but not including) n.

See it in code

1Start simple

First, let's just look at the numbers range makes. Wrap it in list(...) to see them all at once:

python
print("range(5) gives:", list(range(5)))
print("range(3) gives:", list(range(3)))
Run it — range hands back a run of numbers:
range(5) gives: [0, 1, 2, 3, 4]
range(3) gives: [0, 1, 2]

See how range(5) stopped at 4, not 5? It makes five numbers, but it starts at 0.

2A step further

Those numbers are counters you can use. A loop walks through range(5), and we turn each number i into an x-spot — sliding a little further across each time:

python
for i in range(5):
    print("star", i, "at x", 90 + i * 80)
Run it — each number becomes a position:
star 0 at x 90
star 1 at x 170
star 2 at x 250
star 3 at x 330
star 4 at x 410

90 + i * 80 turns 0, 1, 2, 3, 4 into 90, 170, 250 … — five evenly spaced spots from one line of math. Next we hand those spots to real stars.

3In our world

Now put it on the canvas. The loop counts through range(5), and we place a star at each x-spot — the same 90 + i * 80 from above:

python
from art import Canvas, star

screen = Canvas.create()
Canvas.fill(screen)

print("range(5) gives:", list(range(5)))

for i in range(5):
    star(screen, 90 + i * 80, 250, size=50)
Run it — five numbers, five stars:
range(5) gives: [0, 1, 2, 3, 4]
A row of five yellow stars evenly spaced across a dark navy canvas.

Five numbers from range(5), five stars on the canvas. Change the 5 to 8 and you get eight stars — no extra typing.

The same idea, everywhere

range is the counter behind most loops. Repeat a sound three times, draw ten rows, take twenty steps — range hands the loop the exact numbers to count through. Change the count, change how many times things happen.

Try it yourself

Change range(5) to range(8) — the printout and the stars both grow. Then try range(1, 4), which starts at 1 and gives 1, 2, 3.

The common mistake

Expecting range(5) to include 5. It stops before the number you give, so range(5) is 0, 1, 2, 3, 4. To count up to and include 5, write range(6) or range(1, 6).

What it unlocks

range powers for loops, and once you nest two loops with it you can fill a grid with nested loops.

Older, or want more depth? Read the Teens version →