What is xrange?
harmar at member.fsf.org
Fri Jul 29 21:47:33 CEST 2011
Billy Mays wrote:
> Is xrange not a generator? I know it doesn't return a tuple or list, so
> what exactly is it? Y doesn't ever complete, but x does.
range(n) creates a list containing all the integers 0..n-1. This
is a problem if you do range(1000000), because you'll end up with a >4Mb
list. xrange deals with this by returning an object that pretends to be
a list, but just works out the number needed from the index asked for,
and returns that.
range() can actually be faster in some cases - eg. if iterating
over the same sequence multiple times. xrange has to reconstruct the
integer object every time, but range will have real integer objects. (It
will always perform worse in terms of memory however)
xrange isn't usable in all cases where a real list is needed. For
instance, it doesn't support slices, or any list methods.
FSF ...free as in freedom/
More information about the Python-list