Range Loop

It's a very common task to loop over a range of numbers. Python provides a built-in function called range that generates a sequence of numbers. range can accept one, two, or three parameters.

All three of the following function calls will generate the same sequence of numbers (0 through 9):

range(10)
range(0, 10)
range(0, 10, 1)

The sequence (or, in Python parlance, iterator) generated by range is not a list. But we can still use it in a for loop, as we used a list in the previous section.

Let's see this in action. We'll use a for loop to print the numbers from 0 to 9:

for num in range(10):
    print(num, end=' ')

which produces the following output:

0 1 2 3 4 5 6 7 8 9 

If you need to loop over millions of numbers, range is a better choice than creating a list of numbers, because it takes up considerably less memory.

Let's see a more elaborate example of using range to create list of squares of numbers from 1 to 10:

squares = []

for number in range(1, 11):
    square = number ** 2
    squares.append(square)

print(squares)

In this program we first create an empty list of squares. Then we loop over the numbers from 1 to 10 and append the square of each number to the list. Finally, we print the list.

Here's the output of the program:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Take time to study this program and make sure you understand how it works. The best way to do this is to run the program and experiment with it by introducing small changes and observing the output. If at a particular run you get an error, try to understand the error message and fix the error.