In Python 2, use
for i in xrange(1000):
pass
In Python 3, use
for i in range(1000):
pass
Performance figures for Python 2.6:
$ python -s -m timeit '' 'i = 0
> while i < 1000:
> i += 1'
10000 loops, best of 3: 71.1 usec per loop
$ python -s -m timeit '' 'for i in range(1000): pass'
10000 loops, best of 3: 28.8 usec per loop
$ python -s -m timeit '' 'for i in xrange(1000): pass'
10000 loops, best of 3: 21.9 usec per loop
xrange
is preferable to range
in this case because it produces a generator rather than the whole list [0, 1, 2, ..., 998, 999]
. It'll use less memory, too. If you needed the actual list to work with all at once, that's when you use range
. Normally you want xrange
: that's why in Python 3, xrange(...)
becomes range(...)
and range(...)
becomes list(range(...))
.