Is "for x in range(3): print x" guaranteed to print "0, 1, 2" in that order?
python
Solution
Yes it does. It is not the for loop that guarantees anything, but the range function though. `range(3)` gives you an iterator that returns 0, then 1 and then 2. Iterators can only be accessed one element at a time, so that is the only order the for loop can access the elements.
Other iterators (ones not generated by the `range` function for example) could return elements in other orders.
is the loop guaranteed to start at mylist[0] and proceed sequentially (mylist[1], mylist[2], ...)?
When you use a for loop, the list gets used as an iterator. That is, the for loop actually does not index into it. It just keeps calling the `next` function until there are no more elements. In this way the for loop itself has no say in what order elements gets processed.
Problem
Is a loop of the form ``` for x in range(3): print x ``` guaranteed to output ``` 0 1 2 ``` in that order? In other words, if you loop over a list with a `for item in mylist` statement, is the loop guaranteed to start at `mylist[0]` and proceed sequentially (`mylist[1]`, `mylist[2]`, ...)?