In this Python tutorial, you will learn what range() function is, its syntax, and how to use it to generate a sequence of numbers in Python programs.
Python range()
range() function generates a sequence of integers. When you need a sequence of integers, range() is preferred over list. The reason being, range() generates the elements only on demand, unlike list, where list stores all the elements in memory.
Syntax
Following is the syntax of range() function.
range(start, stop[, step])
range() function returns an object that generates a sequence of integers. These integers range from from start (inclusive) to stop (exclusive) with adjacent integers separated by step. range(i, j) produces i, i+1, i+2, …, j-1. For example, range(2, 20, 3) means 2, 5, 8, 11, 14, 17
.
start has a default value of 0. And you can just provide stop as argument to range() function. So range(4) means a sequence of integers 0, 1, 2, 3
.
Examples
1. Python range()
In this example, we will create a range object which represents a sequence that starts at 3 and stops before 40 insteps of 5.
Python Program
myrange = range(2, 20, 3)
print(myrange)
print(list(myrange))
Output
range(2, 20, 3)
[2, 5, 8, 11, 14, 17]
2. Python range() with no start
The default value of start is zero. Therefore, if you do not provide start, the range will start from zero.
Also, you have to note that, if you do not provide start, you cannot give step value also. In this case, range() function accepts only one argument, and that is stop.
As the default value of step is 1, we will get elements starting from zero, until stop, insteps of 1.
In this example, we will create a range object which represents a sequence that ends before 8.
Python Program
myrange = range(8)
print(myrange)
print(list(myrange))
Output
range(0, 8)
[0, 1, 2, 3, 4, 5, 6, 7]
You would observe that range(8) would be translated to range(0, 8).
3. Python range() with specific start and end
In this example, we will create a range object which represents a sequence that starts at 4 and ends before 8. As the default value of step is 1, we should get sequence of integers 4, 5, 6, 7.
Python Program
myrange = range(4, 8)
print(myrange)
print(list(myrange))
Output
range(4, 8)
[4, 5, 6, 7]
You would observe that range(8) would be translated to range(0, 8).
4. Iterate over range()
We can iterate over Python range() using For loop. The following program demonstrates the same.
Python Program
myrange = range(2, 20, 3)
for i in myrange :
print(i)
Output
2
5
8
11
14
17
Reference tutorials for the above program
Conclusion
Concluding this Python Tutorial, we learned what Python range() function is, its syntax, what object does it return, how to use it to generate a sequence of integers, and how to iterate over the elements of range object.