Javaexercise.com

Python range() Method

Python range() method is a built-in method. It is used to create an immutable sequence of numbers. It returns an object of sequence that behaves like list but it is not. The object belongs to the range class.


Signature

range(stop)
range(start, stop[, step])

Parameter Description
Start (Optional) It is starting value of the range. Its default value is 0.
Stop (Required) It is end value of the range.
Step (Optional) It is step value of the range. Its default value is 1.


Return

It returns an object of range class.

Note: All the arguments of range() must be integer.


Python range() Method Example

Let’s first understand, how to create a range and what type of object it returns?

# Creating an empty range
r = range(0)
# Displaying range object
print(r)
# Displaying type of object
print(type(r))

 Output:
 range(0, 0)
 < class 'range'>

Python range() method Example : Creating Range Object

# Creating a range
r1 = range(5)
# Providing start and stop arguments
r2 = range(1,5)
# Providing all three arguments
r3 = range(1,5,1)
# Displaying range objects
print(list(r1))
print(list(r2))
print(list(r3))

 Output:
 [0, 1, 2, 3, 4] # range starts from 0, if start argument is not provided.
 [1, 2, 3, 4]
 [1, 2, 3, 4]

Python range() method Example : range object can be accessed using indices

Range elements can be accessed using indices. See the example.

# Creating a range
r1 = range(1,10,2)
# Displaying range elements
print(list(r1))
# Accessing element using index
print("Element at second index is: ",r1[2])

 Output:
 [1, 3, 5, 7, 9]
 Element at second index is: 5