When I do:
set('zbc')
I get as a result:
{'b' , 'z' , 'c'}
And when I start another python code and type the same thing, I get different order? Why is that? Is there a way to get the same order everytime? thanks.
When I do:
set('zbc')
I get as a result:
{'b' , 'z' , 'c'}
And when I start another python code and type the same thing, I get different order? Why is that? Is there a way to get the same order everytime? thanks.
Just read this documentation
Sets are unordered collection.
You can use other modules like OrderedDict
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
for key, value in od.items():
print(key, value)
Output :
('a', 1)
('b', 2)
('c', 3)
('d', 4)
Order in set
is not guaranteed as they are based on hash tables and not on balanced trees.
Moreover hashing is randomized when Python starts to avoid denial of service attacks to servers: carefully crafted requests could put servers in O(n)
search times on dictionaries making servers unable to answer in time.
dict
on the other hand has been changed recently and it maintains the insertion order; thus if you only insert elements and later iterated the dictionary the key/value pairs will be in the same order they were when you inserted them.
Instead of a set like
{'c', 'b', 'z'}
you can use a dict like
{'c': None, 'b': None, 'z': None}
on recent CPython the key sequence will be c
, b
and z
(not sure if other Python implementations already aligned on this).