Possible Duplicate:
Only index needed: enumerate or (x)range?
Which of these would be considered better/clearer/faster/more 'Pythonic'? I don't care about the content of the list L
, just how long it is.
a = [f(n) for n, _ in enumerate(L)]
or
a = [f(n) for n in range(len(L))]
If it makes any difference, the function f
makes use of len(list)
as well.
enumerate is faster when you want to repeatedly access the list items at their index. When you just want a list of indices, it is faster to to use len() and range/xrange.
Well, if len(list) is the length of a list, and range(N) is the integers from 0 to N-1, then range(len(list)) is the integers from 0 to 1 less than the length of the list, i.e., all the legal indices of the list.
Instead of using the range() function, we can instead use the built-in enumerate() function in python. enumerate() allows us to iterate through a sequence but it keeps track of both the index and the element. The enumerate() function takes in an iterable as an argument, such as a list, string, tuple, or dictionary.
Using len() With Built-in SequencesThe function returns 0 in each case. This range of numbers includes the integers from 1 to 19 with increments of 2 . The length of a range object can be determined from the start, stop, and step values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With