1. Technology

Beginning Python: Controlling the Flow

By

7 of 7

FOR Loops - Part 2: range() and xrange()

Sometimes it is helpful to be able to just tell the computer to do something a certain number of times without having to type in every item of a range. This is why Python has a special function called range. range() takes two numbers and tells Python to count from the one to the other. By default, it does this in increments of one but can be told to do it in increments of any positive integer imaginable. The basic syntax of range() is as follows:

 range(start, end) 
 
 range(0, 10) 

When the increment element is used, it goes after the end number:

 range(start, end, increment) 
 range(0, 10, 2) 

You can use range() wherever you would use a list. Whether you assign the range to a variable or use it directly in a for condition, the results are the same.

 a = range(1, 10) 
 for i in a: 
 print i 
# (Alternatively:)
 for i in range(1, 10): 
 print i 
output:
1
2
3
4
5
6
7
8
9

A word should be said here about large ranges. range() works by forming the range list when it is called. The full value of that list is then passed around the program whenever the range is needed. This consumes memory and CPU cycles, especially when range() is given a large number of items to amass. Therefore, Python has another range function called xrange(). The syntax of xrange() is exactly the same as range(), but xrange() populates its range list whenever it is accessed, allowing the memory to be freed when the list is not actively used.

Other tutorials in this series: 1 | 2 | 3 | 4 | 5 | 6

  1. About.com
  2. Technology
  3. Python

©2014 About.com. All rights reserved.