Difference between range and xrange ??

Terry Reedy tjreedy at udel.edu
Mon Nov 5 19:38:06 CET 2012


On 11/5/2012 9:23 AM, inshu chauhan wrote:
> what is the difference between range and xrange.. both seem to work the
> same. ?

 >>> range(3)
[0, 1, 2]
 >>> xrange(3)
xrange(3)

You should read the appropriate manual entries before asking trivial 
questions. They say pretty clearly that range returns a list and xrange 
an xrange object.
http://docs.python.org/2/library/functions.html#range
http://docs.python.org/2/library/functions.html#xrange

If you do not understand the entries, quote the part that confuses you 
and say what you are unclear about.

> And which should be used where and in what situations.. ??

The entry for xrange (added after range) tries to explain this. It is 
for situations in which one does not want a list, but only the sequence 
of numbers, especially in situations where the length of the list would 
be large enough to make creating the unneeded list a nuisance.


-- 
Terry Jan Reedy



More information about the Python-list mailing list