Pythonic: range vs enumerate in python for loop [closed]

蓝咒 提交于 2019-12-18 14:54:04

问题


Could you please tell me why it is considered as "not pythonic" when I need the index and the value when looping over a list and use:

a = [1,2,3]
for i in range(len(a)):
  # i is the idx
  # a[i] is the value

but rather it is recommended to use

for idx, val in enumerate(a):
  print idx, val

who defines "pythonic" and why is the latter one better? I mean it's not that much better concerning readability, is it!?

Thanks in advance


回答1:


First of all, the first way is ugly: You either need a separate variable assignment to get the element or use a[i] all the time which could theoretically be an expensive operation. Imagine a being a database cursor: When you iterate it (a.__iter__ being called) the object can safely assume that you are going to iterate over all its items. So all or at least multiple rows could be retrieved at once. When getting the length such an optimization would be stupid though since you surely don't want to retrieve data just because you want the number of items. Also, when retrieving a specific item you cannot assume that other items will be retrieved, too.

Additionally, using enumerate() works with any iterable while range(len()) only works with countable, indexable objects.



来源:https://stackoverflow.com/questions/24150762/pythonic-range-vs-enumerate-in-python-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!