Chapter 23 of 26

range() Function in Python

When working with for loops, you'll often need to generate a sequence of numbers. That's where Python's range() function becomes useful.

For example, if you want to run a loop 5 times, you can simply write:

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

Output:

0
1
2
3
4

What is range()?

The range() function generates a sequence of numbers, commonly used with for loops.

The important thing to remember is that the stop value is not included.

For example:

range(5)

generates:

0, 1, 2, 3, 4

range(stop)

The simplest form takes one argument:

range(stop)

For example:

for number in range(5):
    print(number)

Output:

0
1
2
3
4

When only one value is provided, Python starts from 0.

range(start, stop)

You can also specify where the sequence should start:

for number in range(2, 6):
    print(number)

Output:

2
3
4
5

Here:

start = 2
stop  = 6

The sequence stops before 6.

range(start, stop, step)

The third argument specifies how much the number should change each time.

for number in range(2, 11, 2):
    print(number)

Output:

2
4
6
8
10

Here, the step is 2, so Python increases the number by 2 each time.

Counting Backwards

A negative step lets you count backwards.

for number in range(5, 0, -1):
    print(number)

Output:

5
4
3
2
1

Notice that 0 isn't included because the stop value is exclusive.

Using range() to Repeat Something

You can use range() when you simply want to repeat an operation a certain number of times.

for i in range(3):
    print("Hello!")

Output:

Hello!
Hello!
Hello!

You don't have to use the loop variable if you don't need it.

A common convention is:

for _ in range(3):
    print("Hello!")

The _ indicates that the loop variable isn't needed.

Converting range() to a List

range() produces a range object. If you want to see all its values as a list, you can use list():

numbers = list(range(5))

print(numbers)

Output:

[0, 1, 2, 3, 4]

Common range() Patterns

Here are some patterns you'll use frequently:

range(5)          # 0 to 4
range(1, 6)       # 1 to 5
range(2, 11, 2)   # 2, 4, 6, 8, 10
range(10, 0, -1)  # 10 to 1

A Practical Example

Let's print the numbers from 1 to 10 and calculate their squares:

for number in range(1, 11):
    print(f"{number}² = {number ** 2}")

Output:

1² = 1
2² = 4
3² = 9
...
10² = 100

One Important Thing to Remember

The most common mistake beginners make with range() is forgetting that the stop value is excluded.

So:

range(1, 5)

means:

1, 2, 3, 4

not 1, 2, 3, 4, 5.

Once you understand start, stop, and step, range() becomes a very simple and useful tool for controlling for loops.