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?
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.
Iterating over a List is much much faster than iterating over a set.
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.
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__() .
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'])
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))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With