Diez B. Roggisch wrote:

for i in range(5, len(var)): ...

Better use xrange - it doesn't create an actual list, but instead an iterator enumerating the elements. That way more memory and cpu efficient.

I could've sworn I read somewhere in the past that xrange was supposed to be slower than range in some situation, but at least for some simple cases in Python 2.4, it seems to be about as fast or faster:


> python -m timeit "for i in range(100): a = i*2"
10000 loops, best of 3: 21.8 usec per loop

> python -m timeit "for i in xrange(100): a = i*2"
10000 loops, best of 3: 19.4 usec per loop

> python -m timeit "for i in range(10000): a = i*2"
100 loops, best of 3: 2.18 msec per loop

> python -m timeit "for i in xrange(10000): a = i*2"
100 loops, best of 3: 2.29 msec per loop

> python -m timeit "for i in range(100000): a = i*2"
10 loops, best of 3: 25.5 msec per loop

> python -m timeit "for i in xrange(100000): a = i*2"
10 loops, best of 3: 20.7 msec per loop

I hardly ever use (x)range for anything (because you can almost always use a for loop to loop over items instead), but I'll file this info away mentally for the next time I do. Thanks!

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to