Lesson 03-05: The range()
Function¶
Learning Target: I can use the range function to generate a specific list of numbers.
In the last lesson, we learned about basic for
loop syntax, using the range()
function. But what does the range()
function actually do?
A Basic range()
¶
If we print list(range(5))
, we’ll see the following (don’t worry about list
yet, that’s just how we visualize it):
[0, 1, 2, 3, 4]
If we print list(range(8))
, we’ll see the following:
[0, 1, 2, 3, 4, 5, 6, 7]
Notice a pattern?
So the range()
function returns a list of numbers, which we use the for
loop to loop through. This is very powerful, because it allows us to specify almost any range of numbers.
Generating Ranges¶
The range()
function can take anywhere between one and three numbers. Let’s review how each one works.
With range(b)
¶
The rule for range(b)
should be familiar. range(b)
can be referred to as range(end)
.
Using range(end)
will produce a list of integers starting at 0 and ending at end-1
.
With range(a,b)
¶
Let’s look at a few examples when we feed the range()
function two numbers:
print(list(range(5,7)))
print(list(range(2,10)))
print(list(range(-5,5)))
print(list(range(10,20)))
print(list(range(10,3)))
[5, 6]
[2, 3, 4, 5, 6, 7, 8, 9]
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[]
(0305_ex_1)
Notice the pattern? Let’s see if you got it:
A range()
function with 2 numbers can be referred to as range(start, end)
As a general rule for range(start,end)
, Using range(start,end)
will produce a list of integers starting at start
and ending at end-1
.
With range(a,b,c)
¶
Let’s look at a few examples when we feed the range()
function three numbers:
print(list(range(1,10,1)))
print(list(range(1,10,2)))
print(list(range(1,10,3)))
print(list(range(20,5,-2)))
print(list(range(20,71,10)))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
[1, 4, 7]
[20, 18, 16, 14, 12, 10, 8, 6]
[20, 30, 40, 50, 60, 70]
(0305_ex_2)
Notice the pattern? Let’s see if you got it:
Hopefully you noticed that the third number determines how much the next number in the list will change by. This is called the step. A step can be positive or negative.
A range()
function with 3 numbers can be referred to as range(start, end, step)
As a general rule for range(start,end,step)
, Using range(start,end,step)
will produce a list of integers starting at start
, changing by step
with each number, and stopping before we get past end
.