range()
range() is a built in Python function that generates a
sequence of integers. It is one of the most useful tools you will use
in combination with for loops. Before we look at how to use it, here
is the full signature:
range(stop)
range(start, stop)
range(start, stop, step)
- start the number to begin at. Defaults to
0if not specified. - stop the number to stop at. This value is exclusive, meaning Python stops before reaching it.
- step the increment between each number. Defaults to
1if not specified.
So range(4) produces 0, 1, 2, 3. Not 4.
This trips up a lot of beginners. The stop value is never included
in the output.
range() is an Object
If you try to print range(100) directly you will not see
a list of numbers. You will see this:
range(0, 100)
That is because range() returns a range object,
not a list. It does not generate all the numbers immediately. It waits
until you need them. This makes it very memory efficient. Instead of
storing 100 numbers in memory, Python just remembers the start, stop
and step and generates each number on demand.
Because range is an object it is also an iterable. That means we can loop over it just like a list, tuple or string.
Try the following in the box below:
print(range(100))print(range(0, 100))print(range(0, 100, 2))
Iterating Over range()
Now that we know range is iterable we can use it in a for loop. This is where range becomes extremely powerful. Instead of creating a list of numbers manually, we can just tell Python how many times we want to loop.
Try each of the following and run them one at a time:
for number in range(0, 100):thenprint(number)for number in range(0, 100, 2):thenprint(number)for number in range(100, 0, -1):thenprint(number)
When You Don't Need the Variable
Sometimes you want to use range to control how many times a loop runs
but you do not actually need the number itself inside the loop. In
this case it is common practice in Python to use an
underscore _ in place of the variable
name. This signals to anyone reading your code that the variable is
intentionally unused.
For example if you want to print a message 50 times you do not need the loop variable at all:
Using _ is not a rule, it is a widely adopted convention.
Python will not complain if you use a regular variable name and never
use it, but _ makes your intention immediately clear to
other developers.
range() and list()
We almost always see range() used directly inside a for
loop, but it can also be wrapped in the list() function
to convert the range object into an actual list. This is useful when
you need to store or inspect the sequence of numbers directly.
Try the following in the box below:
print(list(range(10)))print(list(range(0, 20, 2)))print(list(range(10, 0, -1)))
We can also combine this with a for loop. Instead of iterating over the range directly, we iterate over the list that range produces. The result is the same but now you can clearly see the full sequence that is being looped over. Try the following:
for _ in range(5):thenprint(list(range(10)))
Notice that the same list is printed 5 times. The
outer range(5) controls how many times the loop runs and
the inner list(range(10)) generates the full list on
each iteration.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named range.py in your part46 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Basic range()
-
Task: Use
range()to print the numbers 1 to 10. Remember that range is exclusive of the stop value so think carefully about where you stop. - Goal: Write a second loop that prints only the even numbers between 1 and 20 using the step argument. Write a comment explaining how the step argument controls the output.
Exercise 2: Counting Down
-
Task: Use
range()with a negative step to count down from 10 to 1 and print each number. -
Goal: Modify the loop to print
"Blast off!"after the countdown finishes. Write a comment explaining how a negative step works and why the stop value must be 0 and not 1 to include 1 in the output.
Exercise 3: range() and list()
-
Task: Use
list(range())to create and print the following three lists in a single file: - All numbers from 0 to 20
- All even numbers from 0 to 20
- All odd numbers from 1 to 20
- Goal: Write a comment next to each one explaining the start, stop and step values you used and why.
Exercise 4: Using _
-
Task: Use
range()and the_convention to print the following: - Your name 10 times
list(range(5))printed 3 times-
Goal: Write a comment explaining when and why we
use
_instead of a named variable in a for loop.
Exercise 5: range() with a Condition
-
Task: Use
range(1, 101)to loop through the numbers 1 to 100. -
Goal: Write a conditional block inside the loop
that prints
"fizz"if the number is divisible by 3,"buzz"if the number is divisible by 5, and"fizzbuzz"if it is divisible by both. Print the number itself if none of the conditions are met. Write a comment explaining how the modulo operator%is used to check divisibility.
Don't Forget to commit and Push!