Python range()

In this tutorial, we will learn what range() function is, its syntax and how to use it in Python programs.

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.

Python range()

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.

Example 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))
Try Online

Output

range(2, 20, 3)
[2, 5, 8, 11, 14, 17]

Example 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))
Try Online

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).

Example 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))
Try Online

Output

range(4, 8)
[4, 5, 6, 7]

You would observe that range(8) would be translated to range(0, 8).

Iterate over range()

We can iterate over Python range() using for loop. Following example demonstrates the same.

Python Program

myrange = range(2, 20, 3)

for i in myrange :
    print(i)
Try Online

Output

2
5
8
11
14
17

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.