range() function in Python

The range() function in Python is the constructor to the class range. Range objects represent immutable sequence of integers.

Built-in Functions Updated 8 Mar 2017 1 min read

Function Name

range

Function Signature

range(stop)

range(start, stop[, step])

Function Overview:

  • The range() function is the constructor for the range class and return a range object

  • Range in is an immutable sequence type in Python.

  • Ranges represent a sequence of integers starting and ending at specified values.

  • Ranges have intervals.

  • The next value of a python range is defined by

nextvalue = previous value + interval value

where nextvalue < stop value

  • Ranges are preferred over a list or tuple because they do not store the whole sequences.

  • Regardless of the length of the sequences they represent, range objects occupy the same amount of memory as only the starting value, stopping value and the interval are specified.

  • Ranges have the default start value of zero.

  • The default value for the interval is one, and is represented by the step parameter.

  • Ranges support operations like accessing the elements by index, slicing and the other common sequence operations as defined by collections.abc.Sequence interface.

  • Since ranges represent integer sequences, the sequence represented by a range could contain negative numbers as well.

  • As with any sequence in Python negative indexes represent positions from the end of the sequence.

Example

python
 # Range - starting from zero and ending at 9

print("Integers zero to 9:")

r1 = range(10)

for elem in r1:

    print(elem)

print("===")

# Range of even numbers less than 15

print("Even numbers less than 15:")

r1 = range(2,15,2)

for elem in r1:

    print(elem)

print("===")

# Range of odd numbers less than 15

print("Odd numbers less than 15:")

r1 = range(1,15,2)

for elem in r1:

    print(elem)

Output

Output
Integers zero to 9:

0

1

2

3

4

5

6

7

8

9

===

Even numbers less than 15:

2

4

6

8

10

12

14

===

Odd numbers less than 15:

1

3

5

7

9

11

13