The Range Class In Python

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 an 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 it 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:

# 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:

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:

# 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:

10

8

6

4

2

0

-2

-4

-6

-8

-10


Copyright 2020 © pythontic.com