Python Range Function

Python offers different inbuilt functions, one such function is range. In this tutorial, we will learn about range functions in Python with examples.

The range function

Rather than being a function, the range type is an immutable sequence of numbers. Ranges implement all of the common sequence operations except concatenation and repetition.

Syntax of the range function

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

The arguments to the range constructor must be integers.

Parameters

  • start – An integer value to specify the start position(Optional, default start position is 0)
  • stop – An integer value to specify the stop position, it is not included in the output
  • step – An integer value to specify the increment (Optional, the default step size is 1)

Returns

  • Range object

The advantage of the range type over a regular list or tuple 

The main advantage of a range object it will take the same amount of memory no matter the size of the range it represents. It stores only start, stop, and step values and calculates the sub-range value as needed.

Examples

Let’s understand range function with some examples.

Range function with a stop position only

In this example, the stop value is 10. So the result is a sequence starting from 0 to 9.

numbers = list(range(10))
print(numbers)

Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Range function with stop size 0 :

>>> list(range(0))
[]
>>> list(range(1, 0))
[]

Range function with a start position

To print 1 to 10 we can write it as :

numbers = list(range(1, 11))
print(numbers)

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Range function with a step size

In this example, we will give step size to the range function. To print the odd numbers between 1 and 20:

# To get odd numbers between 1 and 20
odd_numbers = list(range(1, 20, 2))
print(odd_numbers)

Output

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Range function with for loop

We can also use for loop to iterate the elements of the range object.

for i in range(0, 20, 5):
  print(i)

Output

0
5
10
15

Supported operations on the range object

The range object implements collections.abc.Sequence ABC (abstract base class). It supports containment tests( check whether an element exists in range), element index lookup, and slicing. However, the range object does not support concatenation and repetition.

We can find the length of the range object using len function.

r = range (1,20,2)

print(f"Length of range object: {len(r)}")

Output

Length of range object: 10

To check element exists in a range object:

>>> r = range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True

Accessing elements using an index.

>>> r.index(10)
5
>>> r[5]
10

Finally, slicing the range object.

>>> r[:5]
range(0, 10, 2)
>>> r[-1] #last element
18

Conclusion

There you have it, all about Python range functions. Read about the randrange and randint function in Python.