Python range() Method

The range() constructor method returns an object of the range class, which is an immutable sequence type. The range() method returns the immutable sequence numbers between the specified start and the stop parameter, increment by step parameter.

Syntax:

range(start, stop, step)

Parameters:

  1. start: (Optional) An integer to start counting from, defaults to 0.
  2. stop: An integer to stop the count at.
  3. step: (Optional) An integer that indicates the incremental value from start parameter value, defaults to 1.

Return Value:

Returns an immutable sequence object of numbers.

The following example demonstrates the range() method.

Example: range()
num_range = range(5) #start=0, stop=5, step=1
print(type(num_range))
print(num_range)
print('Values = ', num_range[0], num_range[1], num_range[2], num_range[3], num_range[4])
Output
<class 'range'>
range(0, 5)
Values =  0 1 2 3 4

In the above example, the range(5) returns the range object with the default start 0, stop 5, and default step 1. The range is an immutable sequence, so that values can be accessed by passing indexes in the square brackets [].

The in operator is used to check whether the particular number exists in the range sequence or not, as shown below.

Example:
num_range = range(5) #start=0, stop=5, step=1
print(0 in num_range)
print(4 in num_range)
print(5 in num_range)
print(6 in num_range)

Output
True
True
False
False

The range object can be converted to the other iterable types such as list, tuple, and set.

Example: Convert Range to other Iterables
print(list(range(5)))
print(tuple(range(5)))
print(set(range(5)))

Output
[0, 1, 2, 3, 4]
(0, 1, 2, 3, 4)
{0, 1, 2, 3, 4}

The following creates a different range objects with different values of start and step parameters.

Example: range()
num_range1 = range(1, 5) #start=1, stop=5, step=1
print('range(1, 5) = ', list(num_range1))

num_range2 = range(1, 10, 2) #start=1, stop=10, step=2
print('range(1, 10, 2) = ', list(num_range2))

num_range3 = range(0, 20, 5) #start=0, stop=20, step=5
print('range(0, 20, 5) = ', list(num_range3))

num_range4 = range(-5, -1) #start=-5, stop=-1, step=1
print('range(-5, -1) = ', list(num_range4))

num_range5 = range(-5) #start=0, stop=-5, step=1
print('range(-5) = ', list(num_range5))
Output
range(1, 5) = [1, 2, 3, 4]
range(1,10, 2) = [1, 3, 5, 7, 9]
range(0, 20, 5) = [0, 5, 10, 15]
range(-5, -1) = [-5, -4, -3, -2]
range(-5) = []

The == and != operator is used to compare two range objects and determines that they have same start, stop, and step parameters.

Example: range()
num_range1 = range(1, 5) 
num_range2 = range(1, 10, 2) 
num_range3 = range(1, 5) 

print(num_range1 == num_range2)
print(num_range1 == num_range3)
Output
False
True

The range() function is generally used with for loops, as shown below.

Example: range() with For Loop
for i in range(5):
	print(i)
Output
0
1
2
3
4
Want to check how much you know Python?