Are the two methods of iterating over a list completely equivalent?


A bit of a conceptual question:
Are the two methods of iterating over a list (copied below, from 12.16) completely identical?

The second method "feels" better to me, because I feel like I'm controlling exactly when in this loop the action code (here "print ... ") will act. I.e., I'm telling the code exactly which index to operate over. Or should I be confident that method 1 will absolutely always work sequentially through the list (suggesting no difference other than preference in syntax)?

I'm concerned for applications where the loop needs to act in an important sequence.

Any input/opinion from more experienced coders is much appreciated!

for item in list:
    print item

for i in range(len(list)):
    print list[i]


The range function creates a list, the difference is that you iterate over that list instead, and then use its values as indexes.

If you just need each value, then iterate through just the container (lists etc)

It is the value type that controls how the iteration happens, if you loop through a list then the for-loop will ask the list type how to do so and get an iterator which produces each next value when asked to do so.

Somewhat like this:

iterable = range(5)
iterator = iter(iterable)
next(iterator)  # 0
next(iterator)  # 1
next(iterator)  # 2
next(iterator)  # 3
next(iterator)  # 4
next(iterator)  # StopIteration exception