Range function

Revision as of 14:40, 10 April 2011 by Smitschu (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The range function in Python generates a sequence of integers. It's most frequently used in for-loops, to define the values the iterator variable should take on.

Basics

The format for the range function is

range([start], stop, [step])

Range will return an iterator whose values are start, start+step, start+2*step, ... up to but not including stop. The start and step parameters are optional, if not specified start defaults to 0 and step defaults to 1.

If the specified parameters makes the range impossible (for example, if stop is smaller than start, but step is positive), then range will return an empty iterator.

Note that the sequence range returns is different from the other sequence types. It's much more efficient, especially for large ranges, to generate the elements on the fly than to generate them all beforehand and store them in memory. If you need a real list for some reason you can call the type conversion function list on the range as shown below:

range(5)       # returns an iterator that generates the numbers 0,1,2,3,4
list(range(5)) # returns the list [0,1,2,3,4]

Examples

Function Call      Output      Remarks
---------------------------------------
range(5)           0,1,2,3,4   Remember, endpoints aren't included!
range(3,8)         3,4,5,6,7   
range(3,8,2)       3,5,7       
range(4,-1,-1)     4,3,2,1,0   
range(0,-5)        none        This range is impossible, because end<start

Common Usage

The simplest use of range is in a for loop, iterating through a list. For example, the following will add 1 to each element of myList:

for i in range(len(myList)):
    myList[i] += 1

If we wanted to traverse the list in reverse order, we could use:

for i in range(len(myList)-1, -1, -1):
    myList[i] += 1

Note that the range is only computed once in a for loop. Hence, if the length of your list is going to change during the loop (if you're removing elements, say) you shouldn't use a range based on the length of the list, because you'll either get an error when you try to go past the end of the list or stop short. Instead, you can use either

for x in myList:
    if x%2 == 0: # remove all the even elements
        myList.remove(x)

or, if you still need the index, you can use a while loop where you manually increment and test an index variable:

i = 0
while i<len(myList):
    if myList[i]%2 == 0: # remove all the even elements
        del(myList[i])
    i += 1 # don't forget to increment i, or you'll have an infinite loop!