using range() in for loops

Georg Brandl g.brandl-nospam at gmx.net
Wed Apr 5 10:21:02 EDT 2006


AndyL wrote:
> Paul Rubin wrote:
>> Normally you'd use range or xrange.  range builds a complete list in
>> memory so can be expensive if the number is large.  xrange just counts
>> up to that number.
> 
> so when range would be used instead of xrange. if xrange is more 
> efficient, why range was not reimplemented?

Because of backwards compatibility. range() returns a list, xrange() an
iterator: list(xrange(...)) will give the same results as range(...).

In for loops, using xrange instead of range makes no difference since the
loop only iterates over the range. But it's a problem when someone just
does

l = range(100)

and assumes that he's got a list, probably doing

l.remove(5)

and so on.

In Python 3000, plans are that range() will be the same as xrange() is now,
and anyone needing a list can call list(range(...)).

Georg



More information about the Python-list mailing list