Oct. 15, 2012

Python Range Function

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
http://www.python.org

Share this article

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 

Download Our Free Guide To Learning Python

* indicates required

Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.