CodeMIRAI
0 XP

The range() function

2 min read 8 runnable examples Quiz included

range() produces a sequence of whole numbers. Paired with for, it is how you repeat something a set number of times.

range(stop)

Python
for i in range(5):
    print(i)

range(5) gives 0, 1, 2, 3, 4: five numbers, starting at 0, stopping before 5. That "stop before" rule is the same as slicing.

range(start, stop)

Python
for i in range(1, 6):
    print(i)

range(start, stop, step)

Python
for i in range(0, 21, 5):
    print(i)

A negative step counts down:

Python
for i in range(10, 0, -1):
    print(i, end=" ")
print("Liftoff!")

Repeating a fixed number of times

When you don't need the number itself, the convention is to call the variable _:

Python
for _ in range(3):
    print("Hip hip hooray!")

A multiplication table

Python
n = 7
for i in range(1, 11):
    print(f"{n} x {i:2} = {n * i:3}")

range is lazy

A range does not build a list of numbers in memory; it produces each number when asked. That's why range(1_000_000_000) is instant. To see the numbers as a list, convert it:

Python
print(range(5))
print(list(range(5)))
print(list(range(2, 12, 3)))
print(len(range(0, 100, 7)))

Looping over indexes

You can loop over positions with range(len(...)), but enumerate() is usually clearer:

Python
colours = ["red", "green", "blue"]
for i in range(len(colours)):
    print(i, colours[i])
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.