range(len(list)) or enumerate(list)?
Some quick timing runs seem to give the 2nd option using range()
a slight edge over enumerate()
:
timeit a = [f(n) for n, _ in enumerate(mlist)]
10000 loops, best of 3: 118 us per loop
timeit a = [f(n) for n in range(len(mlist))]
10000 loops, best of 3: 102 us per loop
and just for fun using xrange()
(Python v2.7.2)
timeit a = [f(n) for n in xrange(len(mlist))]
10000 loops, best of 3: 99 us per loop
I would favor readable code first, then using xrange()
if available (i.e., Pre-Python v 3.x), followed by range()
and enumerate()
.
The (x)range solution is faster, because it has less overhead, so I'd use that.
In Python 2.x, use xrange
instead of range
, because xrange
uses less memory, because it doesn't create a temporary list. In Python 3.x, there is only range
, which is the less-memory version.
Thus, in Python 2.x, iterating over a range(n)
uses O(n) memory temporarily, and iterating over an xrange(n)
uses O(1) memory temporarily. Runtime is O(n) for both.
I would say that as you aren't using the "_" attribute from the enumarate function then use range as it is more readable that way.