-2

Possible Duplicate:
What is the difference between range and xrange?

Currently I am learning Python. I found that there are two method representing a range when using for loop, which are range() and xrange(). Can anyone give me some ideas about the difference between these two ways and what are the suitable scenarios for each one of them respectively? Thanks !

Community
  • 1
  • 1

1 Answers1

4

pydoc is your friend in these situations!

% pydoc range

Help on built-in function range in module __builtin__:

range(...)
    range([start,] stop[, step]) -> list of integers

    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.

Also online here.

Versus:

% pydoc xrange

Help on class xrange in module __builtin__:

class xrange(object)
 |  xrange([start,] stop[, step]) -> xrange object
 |  
 |  Like range(), but instead of returning a list, returns an object that
 |  generates the numbers in the range on demand.  For looping, this is 
 |  slightly faster than range() and more memory efficient.

Also online there!

johnsyweb
  • 136,902
  • 23
  • 188
  • 247