+ 1
What's the difference between iteration by index and by items in a list? #python3
for example: somelist for i in somelist: for i in range(len(somelist)): what's the difference between two above? and when should I use which? Thanks.
1 Answer
+ 1
The latter is more code (so less readable, easier to mess up) and slower. Besides iterating, you're going to use the values in the list. With the former approach, values are extracted from the list as part of iteration itself:
for value in some_list:
do_something(value)
With the latter approach you're getting only the index. Extra lookup is needed to get the value:
for i in range(len(some_list)):
value = some_list[i]
do_something(value)