range() vs xrange() Python2|3 issues for performance

Stefan Behnel stefan_ml at behnel.de
Tue Aug 2 05:20:41 EDT 2011


harrismh777, 02.08.2011 09:12:
> With Python2 you basically have two ways to get a range of numbers:
> range() , which returns a list, and
> xrange() , which returns an iterator.
>
> With Python3 you must use range(), which produces an iterator; while
> xrange() does not exist at all (at least not on 3.2).

That's a good thing. There should be one - and preferably only one - 
obvious way to do it.

iterable: range(N)
list: list(range(N))
tuple: tuple(range(N))
set: set(range(N))
...

Less special cases in the language.


> This brought up the whole range() xrange() thing for me again because
> Python in any case is just not fast enough (no brag, just fact). So my
> perfect number stuff is written in C, for the moment.

Or use Cython or PyPy, both of which are simpler ways to get your code up 
to speed.


> The interesting thing to note is that
> xrange() on Python2 runs "considerably" faster than the same code using
> range() on Python3.

Are you sure that's due to Py3 range() vs. Py2 xrange()? Py3 has a 
different implementation for integers (which is still being optimised, 
BTW). That's much more likely to make a difference here.

What version of Py3 were you using? If you used the latest, maybe even the 
latest hg version, you will notice that that's substantially faster for 
integers than, e.g. 3.1.x.

Stefan




More information about the Python-list mailing list