Pythonic: vs range lists in python for loop

Could you tell me why it is considered “not pythonic” when I need an index and a value when going through the list and use:

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

but it is recommended to use

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

who defines "pythons" and why is the latter better? I mean, this is not much better than readability, right ??

Thank you in advance

+6
source share
1 answer

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 theoretically can be an expensive operation. Imagine that a is a database cursor. When you repeat it ( a.__iter__ ), the object can safely assume that you are going to a.__iter__ over all its elements. Thus, all or at least several lines can be obtained at once. If you get the length, such an optimization would be stupid, although since you, of course, do not want to receive data just because you want the number of elements. In addition, when you receive a specific item, you also cannot assume that other items will also be found.

In addition, using enumerate() works with any iterative , and range(len()) only works with countable, indexable objects.

+8
source

Source: https://habr.com/ru/post/970648/


All Articles