Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32771

Re: Difference between range and xrange ??

Date 2012-11-05 09:36 -0500
From Dave Angel <d@davea.name>
Subject Re: Difference between range and xrange ??
References <CAFqGZRGnKNsw6W-Tc+JahziuYgRXPt=mp6w5i+ecUBrNyuwSzA@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.3285.1352126226.27098.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Difference between range and xrange ?? Dave Angel <d@davea.name> - 2012-11-05 09:36 -0500

csiph-web