The range class in Python

The range class represents an immutable sequence of integers. Range does not support floating point numbers. Range can create integer sequences in positive, negative and in both directions. To produce a sequence of floating point numbers the numpy.arange() can be used.

Range Updated 20 Sep 2019 1 min read

Overview

  • The Python class range represents a sequence of numbers. Similar to a tuple which is an immutable sequence, a range is also immutable.
  • An immutable sequence cannot be added or removed elements from it.
  • Range is used in for loops to perform specific number of iterations based on a value, which is decremented or incremented by a number till a boundary value is reached.
  • Range cannot produce the same number twice. The sequence should be increasing or decreasing all the times. The default value for the parameter step is 1 and it cannot be 0.
  • Range does not allow any of its parameter to be a float. Hence, Range cannot be used to produce a continuous distribution. The numpy.arange() function can be used to produce an ndarray of floating point numbers.

Example - Increasing range

python
# Print an increasing sequence with default values for start and step parameters

print("An increasing sequence produced by range class:");

stop = 5;

for i in range(stop): # default values for start and step which is 1

    print(i);

print("Odd number series produced by range class :");

start = 1;

stop  = 10;

step  = 2;

for i in range(1, 10, 2):

    print(i);

Output

Output
An increasing sequence produced by range class:

0

1

2

3

4

Odd number series produced by range class:

1

3

5

7

9

Example - Decreasing range

python
# Create a sequence of numbers spanning from -10 to +10 using the range class

start = 10;

stop  = -12;

step  = -2;

for j in range(start, stop, step):

    print(j);

Output

Output
10

8

6

4

2

0

-2

-4

-6

-8

-10