Does the for / in construct keep the loop?

Is it common for the / in operator to state that the list iterates in order?

my_list = [5,4,3,2] for i in my_list print(i) 

That is, the cycle above is guaranteed to print 5 4 3 2 each time?

+6
source share
4 answers

A for loop iteration order is controlled by any object that iterates. Iterating over an ordered collection, such as list , is guaranteed to iterate over the items in list order, but repeating over an unordered collection such as set does not guarantee order.

+10
source

When you iterate over a sequence (list, tuple, etc.), the order is guaranteed. Hash structures (dict, set, etc.) have their own order - but for this structure, the order will be the same every time. If you add or remove an item, the order may be different.


Consider the following code: I make a set of five elements and then print it with four identical loops for . The order is the same. Then I add two elements; it breaks the order.

 my_set = set(["Apple", "Banana", "Casaba", "Dinner", "Eggplant"]) for food in my_set: print food, print "\n" for food in my_set: print food, print "\n" for food in my_set: print food, print "\n" for food in my_set: print food, print "\n" my_set.add("Fruitcacke") my_set.add("Grape") for food in my_set: print food, print "\n" 

Output:

 Casaba Dinner Apple Eggplant Banana Casaba Dinner Apple Eggplant Banana Casaba Dinner Apple Eggplant Banana Casaba Dinner Apple Eggplant Banana Casaba Fruitcacke Grape Apple Dinner Eggplant Banana 

Please note that the source elements are no longer in the same order: β€œDinner” now appears after β€œApple”.

+2
source

If you want to test it yourself:

 my_list = [5,4,3,2] for _ in range(20): new_list = [] for i in my_list: new_list.append(i) print(my_list == new_list) 

And only for the control case:

 print([2,4,5,3] == my_list) 
+1
source

For lists, yes, since they are ordered data structures in Python.

+1
source

All Articles