The range() function is a very popular and widely used function in Python, especially when you are working with for loops, and sometimes also with while loops. The range() function is worth knowing and mastering because doing so will open a lot of doors: range() is used in everything from controlling the flow of a program to looping through data sets that you are using for data analysis.
The range() function returns a sequence of numbers and is immutable, meaning its value is fixed. The range() function takes one or at most three arguments, namely the start and a stop value along with a step size.
range() was introduced in Python3. In Python2, a similar function, xrange(), was used, which had somewhat different behavior. Among other things, xrange() returned a generator object and consumed less memory, while range(), on the other hand, returns a list or sequence of numbers.
Part of the reason the range() function is useful is because it only stores the start, stop, and step values, so it consumes less memory when compared to a list or tuple.
Python range() Function Syntax
The range() function can be represented in three different ways, or you can think of them as three range() parameters:
range(stop_value): By default, the starting point here is zero.
range(start_value, stop_value): This generates the sequence based on the start and stop value.
range(start_value, stop_value, step_size): It generates the sequence by incrementing the start value using the step size until it reaches the stop value.
Python range() function. Image by Author.
We can also check the type of the range() function by wrapping range() in type().
my_range =range(100)print(type(my_range))# Expected output: <class 'range'>Funcționează cu
Editor de tip „Învăță prin exemple", apasă Tab pentru a intra. Apasă Escape și apoi Tab sau Shift+Tab pentru a naviga afară.
Let's now take a look at a few examples so you can practice and master using range().
Using Python range() to print a sequence of numbers
Let's start with a simple example of printing a sequence of ten numbers, which will cover your first range() parameter. To achieve this, you will be just passing in the stop value. Since Python works on zero-based indexing, hence, the sequence will start with zero and stop at the specified number, i.e., n-1, where n is the specified number in the range() function.
my_range =range(10)for num in my_range:print(num)# Expected output:# 0# 1# 2# 3# 4# 5# 6# 7# 8# 9Funcționează cu
Editor de tip „Învăță prin exemple", apasă Tab pentru a intra. Apasă Escape și apoi Tab sau Shift+Tab pentru a naviga afară.
As expected, the above cell returns a sequence of numbers starting with 0 and ending at 9.
Using Python range() with list()
You could also use the range function as an argument to a list in which case it would result in a list of numbers with a length equal to the stop value as shown below:
Let's now add the third parameter, i.e., the step size to the range() function, and find out how it affects the output. You will specify the start point as 50, the stop value as 1000 with a step size of 100. The below range function should output a sequence starting from 50 incrementing with a step of 100.
my_range =range(50,1000,100)print(my_range)# Expected output: range(50, 1000, 100)Funcționează cu
Editor de tip „Învăță prin exemple", apasă Tab pentru a intra. Apasă Escape și apoi Tab sau Shift+Tab pentru a naviga afară.
It is important to note that the range() function can only work when the specified value is an integer or a whole number. It does not support the float data type and the string data type. However, you can pass in both positive and negative integer values to it. Let's see what happens when you try to pass float values.
for num inrange(0.2,2.4):print(num)# Expected output:# TypeError: 'float' object cannot be interpreted as an integerFuncționează cu
Editor de tip „Învăță prin exemple", apasă Tab pentru a intra. Apasă Escape și apoi Tab sau Shift+Tab pentru a naviga afară.
You would have scratched your head at least once while trying to reverse a linked list of integer values in C language. However, in Python, it can be achieved with the range() function with just interchanging the start and stop along with adding a negative step size. Isn't that so simple? Let's find out!
for num inrange(100,10,-10):print(num)# Expected output:# 100# 90# 80# 70# 60# 50# 40# 30# 20Funcționează cu
Editor de tip „Învăță prin exemple", apasă Tab pentru a intra. Apasă Escape și apoi Tab sau Shift+Tab pentru a naviga afară.
Say you have a list of integer values, and you would like to find the sum of the list, but using the range() function. Let's find out it can be done.
First, you will define the list consisting of integer values. Then initialize a counter in which you will store the value each time you iterate over the list and also add the current list value with the old count value.
To access the elements from the list, you will apply the range() function on the length of the list and then access the list elements bypassing the index i which will start from zero and stop at the length of the list.
list1 =[2,4,6,8,10,12,14,16,18,20]
count =0for i inrange(len(list1)):
count = count + list1[i]print(count)print('sum of the list:', count)# Expected output:# 2# 6# 12# 20# 30# 42# 56# 72# 90# 110# sum of the list: 110Funcționează cu
Editor de tip „Învăță prin exemple", apasă Tab pentru a intra. Apasă Escape și apoi Tab sau Shift+Tab pentru a naviga afară.
Using range() with itertools to concatenate a list
You could also concatenate two or more range() functions using the itertools package class called chain. And not just the range function, you could even concatenate list, tuples, etc. Remember that chain method returns a generator object, and to access the elements from that generator object, you can either use a for loop or use list and pass the generator object as an argument to it.
from itertools import chain
a1 =range(10,0,-2)
a2 =range(30,20,-2)
a3 =range(50,40,-2)
final = chain(a1,a2,a3)print(final)#generator object# Expected output: <itertools.chain object at 0xae6330>Funcționează cu
Editor de tip „Învăță prin exemple", apasă Tab pentru a intra. Apasă Escape și apoi Tab sau Shift+Tab pentru a naviga afară.
You can apply equality comparisons between range() functions. Given two range() functions, if they represent the same sequence of values, then they are considered to be equal. Having said that, two equal range() functions don't need to have the same start, stop, and step attributes. Let's understand it with an example.
As you can observe from the above outputs, even though the parameters of the range() function are different, they are still considered to be equal since the sequence of both the functions are the same. In the second example, changing the step size makes the comparison False.
Conclusion
Congratulations on finishing the tutorial. You might want to tinker around a bit with the range() function and find a way to customize it for accepting data types other than just integers.
If, after reading, you feel like could benefit from practicing Python functions, check out our Python Functions and our Beginner's Guide to Python for Loops tutorials. For a structured learning path, take a look at our Writing Efficient Python Code DataCamp course, which not only covers the range() function in detail but also helps with more general coding concepts to help you write really efficient code without a lot of overhead.
A comprehensive introductory tutorial to Python loops. Learn and practice while and for loops, nested loops, the break and continue keywords, the range function and more!
The
range()function is a very popular and widely used function in Python, especially when you are working withforloops, and sometimes also withwhileloops. Therange()function is worth knowing and mastering because doing so will open a lot of doors:range()is used in everything from controlling the flow of a program to looping through data sets that you are using for data analysis.If you are just getting started in Python and would like to learn more, take DataCamp's Introduction to Data Science in Python course.
What is the range() Function in Python?
The
range()function returns a sequence of numbers and is immutable, meaning its value is fixed. Therange()function takes one or at most three arguments, namely thestartand astopvalue along with astepsize.range()was introduced in Python3. In Python2, a similar function,xrange(), was used, which had somewhat different behavior. Among other things,xrange()returned a generator object and consumed less memory, whilerange(), on the other hand, returns a list or sequence of numbers.Part of the reason the
range()function is useful is because it only stores thestart,stop, andstepvalues, so it consumes less memory when compared to a list or tuple.Python range() Function Syntax
The
range()function can be represented in three different ways, or you can think of them as threerange()parameters:range(stop_value): By default, the starting point here is zero.range(start_value, stop_value): This generates the sequence based on the start and stop value.range(start_value, stop_value, step_size): It generates the sequence by incrementing the start value using the step size until it reaches the stop value.We can also check the type of the
range()function by wrappingrange()intype().Python range() Function Examples
Let's now take a look at a few examples so you can practice and master using
range().Using Python range() to print a sequence of numbers
Let's start with a simple example of printing a sequence of ten numbers, which will cover your first
range()parameter. To achieve this, you will be just passing in thestopvalue. Since Python works on zero-based indexing, hence, the sequence will start with zero and stop at the specified number, i.e.,n-1, wherenis the specified number in therange()function.As expected, the above cell returns a sequence of numbers starting with
0and ending at9.Using Python range() with list()
You could also use the range function as an argument to a list in which case it would result in a list of numbers with a length equal to the stop value as shown below:
Making use of start, stop, and step in Python range()
Next, let's look another way of working with the
range()function. Here you will specify bothstartand thestopvalue.Similarly, you can use the
range()function to print the negative integer values as well.Let's now add the third parameter, i.e., the
stepsize to therange()function, and find out how it affects the output. You will specify thestartpoint as 50, thestopvalue as 1000 with astepsize of 100. The below range function should output a sequence starting from 50 incrementing with a step of 100.You will notice that it will print all even numbers.
A note on Python range() and float values
It is important to note that the
range()function can only work when the specified value is an integer or a whole number. It does not support the float data type and the string data type. However, you can pass in both positive and negative integer values to it. Let's see what happens when you try to pass float values.You would have scratched your head at least once while trying to reverse a linked list of integer values in C language. However, in Python, it can be achieved with the
range()function with just interchanging thestartandstopalong with adding a negative step size. Isn't that so simple? Let's find out!Using range() to find the sum of a list
Say you have a list of integer values, and you would like to find the sum of the list, but using the
range()function. Let's find out it can be done.First, you will define the list consisting of integer values. Then initialize a counter in which you will store the value each time you iterate over the list and also add the current list value with the old count value.
To access the elements from the list, you will apply the
range()function on thelengthof the list and then access the list elements bypassing the indexiwhich will start from zero and stop at the length of the list.Using range() with itertools to concatenate a list
You could also concatenate two or more
range()functions using theitertoolspackage class calledchain. And not just therangefunction, you could even concatenate list, tuples, etc. Remember thatchainmethod returns a generator object, and to access the elements from that generator object, you can either use aforloop or uselistand pass the generator object as an argument to it.Python range() and equality comparisons
You can apply equality comparisons between
range()functions. Given tworange()functions, if they represent the same sequence of values, then they are considered to be equal. Having said that, two equalrange()functions don't need to have the samestart,stop, andstepattributes. Let's understand it with an example.As you can observe from the above outputs, even though the parameters of the
range()function are different, they are still considered to be equal since the sequence of both the functions are the same. In the second example, changing thestepsize makes the comparisonFalse.Conclusion
Congratulations on finishing the tutorial. You might want to tinker around a bit with the
range()function and find a way to customize it for accepting data types other than just integers.If, after reading, you feel like could benefit from practicing Python functions, check out our Python Functions and our Beginner's Guide to Python for Loops tutorials. For a structured learning path, take a look at our Writing Efficient Python Code DataCamp course, which not only covers the
range()function in detail but also helps with more general coding concepts to help you write really efficient code without a lot of overhead.