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β.
Prune source share