Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the for/in loop construct preserve order?

Tags:

python

Does an ordinary for/in statement guarantee the list is iterated in order?

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

That is, is the loop above guaranteed to print 5 4 3 2 every time?

like image 958
Tony Ennis Avatar asked Jun 28 '16 21:06

Tony Ennis


People also ask

Does for in loop in order?

The for...in loop will traverse all integer keys before traversing other keys, and in strictly increasing order, making the behavior of for...in close to normal array iteration.

Does enhanced for loop go in order?

3) The enhanced for loop can only iterate in incremental order. we cannot configure it to go in decrement.

Do lists in python preserve order?

Yes, the order of elements in a python list is persistent.


2 Answers

A for loop's iteration order is controlled by whatever object it's iterating over. Iterating over an ordered collection like a list is guaranteed to iterate over elements in the list's order, but iterating over an unordered collection like a set makes almost no order guarantees.

like image 50
user2357112 supports Monica Avatar answered Oct 13 '22 21:10

user2357112 supports Monica


When you iterate over a sequence (list, tuple, etc.), the order is guaranteed. Hashed structures (dict, set, etc.) have their own order -- but for a given structure, the order will be the same each time. If you add or delete an element, the order may then be different.


Consider the folloing code: I make a set of five elements, and then print it out with four identical for loops. The order is the same. Then I add two elements; this upsets 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  

Note how the original elements are no longer in the same order: "Dinner" now comes after "Apple".

like image 40
Prune Avatar answered Oct 13 '22 22:10

Prune