range(len(list)) or enumerate(list)? [duplicate]

2019-01-14 12:26发布

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.

4条回答
成全新的幸福
2楼-- · 2019-01-14 12:33

Assuming you're using Python 2.x, if you use len(), you should use xrange() as it will avoid creating a list of the numbers in the range.

And in this case, I'd go with len() because you are using the indices, not the items in the list.

查看更多
放荡不羁爱自由
3楼-- · 2019-01-14 12:48

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().

查看更多
Bombasti
4楼-- · 2019-01-14 12:54

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.

查看更多
趁早两清
5楼-- · 2019-01-14 12:56

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.

查看更多
登录 后发表回答