BYU logo Computer Science

Range

The range() function creates a range object that is iterable:

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

This will print:

0
1
2
3
4

Notice that the range goes from 0 to 4.

Starting and ending points

By default, range() starts from zero, but you can provide an explicit starting point:

for i in range(4, 10):
    print(i)

This will print:

4
5
6
7
8
9

Iterating over a list

We have previously seen for ... in when iterating over a list

fruits = ['apples', 'apricots', 'avocados']
for fruit in fruits:
    print(fruit)

We can also use range() to iterate over a list:

fruits = ['apples', 'apricots', 'avacados']
for index in range(len(fruits)):
    print(fruits[index])

These will both print:

apples
apricots
avocados

This loop: for index in range(len(fruits)) will produce an index of 0, 1, 2, since the length of the list is 3.

Turning a range into a list

A range object is iterable. This means we can use for ... in to loop through the range, as shown above. This also means we can turn it into a list:

list(range(4, 12))

This creates a list that holds [4, 5, 6, 7, 8, 9, 10, 11].

Stepping in the range

The range() function takes a third parameter, called the step that indicates how many items we should skip as we make the range.

Stepping by 1

This code

for i in range(2, 10, 1):
    print(i)

will print:

2
3
4
5
6
7
8
9

Stepping by 2

This code:

for i in range(2, 10, 2):
    print(i)

will print:

2
4
6
8

Stepping by 3

And this code:

for i in range(2, 10, 3):
    print(i)

will print

2
5
8

Quiz

What python expression using range would you use to create the following sequences?

1, 2, 3, 4, 5
0, 2, 4, 6, 8
-3, 0, 3
5, 4, 3, 2