The Python range()
function creates an iterable of subsequent integers within a given range of values. You can pass either only a stop
argument in which case the range
object will include all integers from 0
to stop
(excluded). Or you can pass start
, stop
, and step
arguments in which case the range object will go from start
to step
using the given step
size. For example, range(3)
results in 0, 1, 2
and range(2, 7, 2)
results in 2, 4, 6
.
Here are some examples of how to use the range()
built-in function:
>>> range(10) range(0, 10) >>> print(range(10)) range(0, 10) >>> print(*range(10)) 0 1 2 3 4 5 6 7 8 9 >>> range(1, 10, 3) range(1, 10, 3) >>> print(*range(1, 10, 3)) 1 4 7
Note that in any case, a range object is returned. The range object is an iterable of values—but the values are only generated as they’re actually needed. You can use the asterisk operator to unpack all values into the print function with print(*range(10))
. Python waits as long as possible to generate the values of the iterable.
Syntax Range Function
You can use the range()
function with three different argument lists: (i) with the stop
argument only, (ii) with the start
and stop
arguments, or (iii) with the start
, stop
, and step
arguments.
Syntax:range(stop)
range(start, stop)
range(start, stop, step)
Arguments | start | An integer defining the first element of the range iterable |
stop | An integer defining the last element. However, this element is not included in the range iterable. | |
step | An integer defining the difference between two subsequent elements in the range iterable. | |
Return Value | range | Returns an iterable range object that allows you to iterate over all values from start to step using the step size. |
Interesting fact: the range()
“function” is technically not a normal function but a constructor method of the range
class. Thus, it creates a new range object.
How Math Genius Gauss Hacked His Teacher’s Exercise With the Range Function
Do you know the following story of the brilliant mathematician Carl Friedrich Gauss? When 8-year old Gauss went to school, his math teacher sought a few minutes of breathing pause. He told his class to solve the problem of adding all subsequent numbers from 1-100: 1+2+3+...+100
.
But as little Gauss promptly reported the solution, the short pause was over before it began.
Surprised (and a bit grumpy as the story goes), the teacher asked the boy how he had come up with a solution so quickly. Gauss explained his simple solution. He organized the sequence into pairs of numbers each summing up to 101: 1+100,2+99,3+98,...,50+51
. There are 50 such pairs, so the total result was 50*101=5050
.
Yet, the modern-time little Gauss would be even lazier. He would type the following one-liner into his mobile Python app: sum(range(1,101))
.
The range()
function returns a sequence starting from the first value (inclusive) and ending in the second value (exclusive). The sum function sums up the values of this sequence. Combining both functions sums up the sequence from 1-100—faster than the brilliant Carl Friedrich Gauss.
Python range() With One Argument Stop
You can use the range()
function with one argument stop
. In this case, the range object goes from start=0
to the stop
argument (excluded) by using the default step size of one.
Here’s the example:
for i in range(5): print(i)
The output is:
0 1 2 3 4
Python range() With Two Arguments Start + Stop
You can use the range()
function with two arguments start
and stop
. In this case, the range object goes from start
to the stop
integer value (excluded) by using the default step size of one.
Here’s the example:
for i in range(1, 5): print(i)
The output is:
1 2 3 4
Python range() With Three Arguments Start + Stop + Step
You can use the range()
function with three arguments start
, stop
, and step
. In this case, the range
object goes from start
to the stop
integer value (excluded) by using the default step size of step
.
Here’s the example:
for i in range(1, 5, 2): print(i)
The output is:
1 3
Interactive Shell Exercise About The Range Function
The following code snippet matches men with women—the idea is to match the i-th man with the i-th woman, assuming that both lists have the same size. How to change the code to accomplish this task?
Exercise: Replace the XXXX
placeholder in the code to match the i-th man with the i-th woman!
You’ll find the solution… after the advertisement! 🙂
Check out my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Publisher Link: https://nostarch.com/pythononeliners
Solution: The following code solves the exercise.
men = ['Bob', 'Carl', 'Frank'] women = ['Ann', 'Alice', 'Liz'] for i in range(len(men)): print(men[i] + ' dances with ' + women[i])
The idea is to use the len()
function to determine the stop
argument automatically with range(len(men))
. Note that range(len(women))
, range(3)
, and range(0, 3)
, and range(0, 3, 1)
would all solve the problem equally well.
Python range() With Negative Step Size
You can also use the range() function with negative step size. The meaning is “move from right to the left using the negative step size as the difference between two subsequent values. In this case, the start argument should be larger than the stop argument.
Here’s an example:
for i in range(4,0,-2): print(i)
The output is:
4 2
Note that the stop
argument is still not included in the range
object.
Range Puzzle
Puzzles are a great and effective way to improve your Python skills. Can you solve this range puzzle?
# Python Puzzle print(sum(range(0,7)))
What is the output of this code snippet?
You can check whether you solved this puzzle correctly, and determine whether you’re a master coder on our Puzzle app Finxter.com:
Are you a master coder?
Test your skills now!
Summary
The Python range()
function creates an iterable of subsequent integers within a given range of values.
You can pass either only a stop
argument in which case the range
object will include all integers from 0
to stop
(excluded). For example, range(3)
results in 0, 1, 2
:
for i in range(3): print(i) ''' OUTPUT: 0 1 2 '''
As an alternative, you can pass start
, stop
, and step
arguments in which case the range object will go from start
to step
using the given step
size. For example, range(2, 7, 2)
results in 2, 4, 6
:
for i in range(2, 7, 2): print(i) ''' OUTPUT: 2 4 6 '''
I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:
Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.