what's the python for this C statement?

Hrvoje Niksic hniksic at xemacs.org
Tue Oct 21 08:35:55 EDT 2008


Lie Ryan <lie.1296 at gmail.com> writes:

> On Mon, 20 Oct 2008 12:34:11 +0200, Hrvoje Niksic wrote:
>
>> Michele <michele at nectarine.it> writes:
>> 
>>> Hi there,
>>> I'm relative new to Python and I discovered that there's one single way
>>> to cycle over an integer variable with for: for i in range(0,10,1)
>> 
>> Please use xrange for this purpose, especially with larger iterations. 
>> range actually allocates a sequence.
>
> Actually that doesn't really matter unless the loop is extremely big (> a 
> million), since range is much faster than xrange for smaller values 
> (which might be the more typical case).

This used to be the case, but is no longer true as of (I think) Python
2.4.  xrange is preferred over range, unless you actually need the
list, of course.  You are right that it is changing, but that is in
Python 3, which only has range in the meaning of today's xrange.

$ python -m timeit 'for i in xrange(10): pass'
1000000 loops, best of 3: 1.13 usec per loop
$ python -m timeit 'for i in range(10): pass'
1000000 loops, best of 3: 1.72 usec per loop



More information about the Python-list mailing list