Difference between range and xrange ??

Dave Angel d at davea.name
Mon Nov 5 15:36:41 CET 2012


On 11/05/2012 09:23 AM, inshu chauhan wrote:
> what is the difference between range and xrange.. both seem to work the
> same. ? And which should be used where and in what situations.. ??
>
>

One difference is that from versions of Python 3.0 and later,  xrange
doesn't exist, and range takes over the behavior of what was formerly
xrange.

So presumably you're asking about Python 2.x


In Python 2.x, range() generates a list, possibly a very large one. 
Sometimes that's exactly what you need.  But other times, you're just
using the list as an iterable, perhaps as a counter, or simply as a way
to make a loop go a fixed number of times.

xrange(), usually more efficient for speed, and certainly for space,
generates an iterable.  So it's interchangeable in a for loop, for example.

In general, if you're going to discard the list immediately after using
it, you should be using the iterable form, not the list form.


In Python 3.x, if you really need a list, you can trivially convert an
iterable into a list with the list "function."

mylist = list(range(4))



-- 

DaveA



More information about the Python-list mailing list