The Range function
The built-in range function in Python is very useful to generate sequences of
numbers in the form of a list.
The given end point is never part of the generated list;
range(10) generates a list of 10 values, the legal indices for items of a
sequence of length 10.
It is possible to let the range start at another number, or to specify a
different increment (even negative;
Sometimes this is called the ‘step’):
Range Examples
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
# You can use range() wherever you would use a list.
a = range(1, 10)
for i in a:
print i
for a in range(21,-1,-2):
print a,
#output>> 21 19 17 15 13 11 9 7 5 3 1
# We can use any size of step (here 2)
>>> range(0,20,2)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> range(20,0,-2)
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
# The sequence will start at 0 by default.
#If we only give one number for a range this replaces the end of range value.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# If we give floats these will first be reduced to integers.
>>> range(-3.5,9.8)
[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
More Reading
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.