The range is an immutable sequence of numbers. The main advantage of using the range type is that the memory occupied is fixed irrespective of the size of the range. This is because the actual contents of the range are not stored, instead they are computed at runtime.

Ranges can be created using:

• range(stop)
• range(start,stop)
• range(start,stop,step)

Note: Only the 1st and 3rd are constructors. In range(start,stop,step), step is an optional parameter. When step is not specified, what we end up with is range(start,stop).

Quick notes about the arguments passed to range():

• If start is not specified, the default value is 0.
• If step is not specified, the default value is 1.
• The step value cannot be zero, a runtime error will be thrown.
• The step value can be negative.
• Stop is always required to be specified.

To check the values of a range, convert the range to a list and print the list. Printing a range directly using print(range_var) will not display the values in the range, since the values are not stored.

Some examples to demonstrate the usage of ranges:

#range(stop)
r1=range(10)
print(list(r1))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#range(start,stop)
r2=range(2,10)
print(list(r2))
[2, 3, 4, 5, 6, 7, 8, 9]

#range(start,stop,step)
r3=range(10,20,2)
print(list(r3))
[10, 12, 14, 16, 18]

#negative step value
r4=range(30,10,-5)
print(list(r4))
[30, 25, 20, 15]


To check if a value is present in a range, the in operator can be used.

r5=range(10,20)
print(15 in r5)
True

print(25 in r5)
False


The comparison operators == and != can be used to compare the values of different ranges.

print(range(0,4,2)==range(0,3,2))
True

print(range(10)!=range(20))
True


The source code for today’s plog is here.