Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration order of sets in Python

If I have two identical sets, meaning a == b gives me True, will they have the same iteration order? I tried it, and it works:

>>> foo = set("abc")
>>> bar = set("abc")
>>> zip(foo, bar)
[('a', 'a'), ('c', 'c'), ('b', 'b')]

My question is, was I lucky, or is this behavior guaranteed?

like image 997
Björn Pollex Avatar asked Aug 04 '10 14:08

Björn Pollex


People also ask

Does Python iterate in order?

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.

Which is faster iterate through set or list Python?

Iterating over a List is much much faster than iterating over a set.

Are sets always in order python?

Summary. In this article, we talked about sets and how to create them in Python. Sets do not allow duplicate items, they are unordered, and the items stored in them cannot be modified. We also saw how to access, add, and remove items in sets using different methods.

What are the iterations in Python?

An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__() .


2 Answers

It wasn't just a coincidence that they came out the same: the implementation happens to be deterministic, so creating the same set twice produces the same ordering. But Python does not guarantee that.

If you create the same set in two different ways:

n = set("abc")
print n

m = set("kabc")
m.remove("k")
print m

...you can get different ordering:

set(['a', 'c', 'b'])
set(['a', 'b', 'c'])
like image 55
Jason Orendorff Avatar answered Oct 25 '22 08:10

Jason Orendorff


You were lucky, the order is not guaranteed. The only thing that's guaranteed is that the sets will have the same elements.

If you need some sort of predictability, you could sort them like this: zip(sorted(foo), sorted(bar)).

like image 41
Cristian Ciupitu Avatar answered Oct 25 '22 08:10

Cristian Ciupitu