简体   繁体   中英

Is “for x in range(3): print x” guaranteed to print “0, 1, 2” in that order?

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] , ...)?

Yes, the builtin list and range will always iterate in the order you expect. Classes define their own iteration sequence, so the iteration order will vary between different classes. Due to their nature set and dict (amongst others) won't iterate in a predictable order.

You can define any iteration sequence you want for a class. For example, you can make a list that will iterate in reverse.

class reversedlist(list):
    def __iter__(self):
        self.current = len(self)
        return self

    def next(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self[self.current]

x = reversedlist([0, 1, 2, 3, 4, 5])
for i in x:
    print i,
# Outputs 5 4 3 2 1 0

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.

Yes, it is.

A python for loop like this:

for e in list:
    print e

can be traslated as:

iterator = list.__iter__()
while True:
    try:
        e = iterator.next()
    except StopIteration:
        break
    print e

So, while the "next" method of the object iterator returns values in the "correct" order you will get the elements in the "correct" order. For python list this is guaranteed to happen.

For more information look here and here

Yes. for loops in Python traverse a list or an iter in order. range returns a list in Python 2.x and an iterator in Python 3.x, so your for x in range(3) loop will indeed always be ordered.

However , the same cannot be said for dict s or set s. They will not be traversed in order - this is because the order of their keys is undefined.

Yes, it starts with the first element of a list and goes to the last.

Not all data types in python do that, such as dicts, but lists certainly do. range(x) certainly will.

Yes.

But with a dictionary there´s no order guaranteed.

Yes. Python docs about For Loop say:

Basically, any object with an iterable method can be used in a for loop in Python ... Having an iterable method basically means that the data can be presented in list form, where there's multiple values in an orderly fashion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM