Why is the order of the elements being changed only when it goes through the function call? what is deciding this order?
# test_set_order.py
def unpack(input):
print('input is {}'.format(input))
result = []
for i in input:
result.extend(i)
return result
print(unpack({'A', 'B'}))
Executing the script above results in different outputs:
$ python test_set_order.py
input is {'B', 'A'}
['B', 'A']
$ python test_set_order.py
input is {'B', 'A'}
['B', 'A']
$ python test_set_order.py
input is {'A', 'B'}
['A', 'B']
$ python test_set_order.py
input is {'B', 'A'}
['B', 'A']
$ python test_set_order.py
input is {'A', 'B'}
['A', 'B']
$ python test_set_order.py
input is {'A', 'B'}
['A', 'B']
This is on python 3.6.5
. On python 2.7.13
you always get the same order
It seems that order only gets changed after the function call. It doesn't happen before:
>>> bla = {'A','B'}; print(bla)
{'A', 'B'}
>>> bla = {'A','B'}; print(bla)
{'A', 'B'}
>>> bla = {'A','B'}; print(bla)
{'A', 'B'}
>>> bla = {'A','B'}; print(bla)
{'A', 'B'}
>>> bla = {'A','B'}; print([i for i in bla])
['A', 'B']
>>> bla = {'A','B'}; print([i for i in bla])
['A', 'B']
>>> bla = {'A','B'}; print([i for i in bla])
['A', 'B']
>>> bla = {'A','B'}; print([i for i in bla])
['A', 'B']
>>> bla = {'A','B'}; print([i for i in bla])
['A', 'B']
UPDATE:
seems that it has to do with the hashing and it is decided when the interpreter starts. This is enough to reproduce:
$ python -c "print({'A', 'B'})"
{'B', 'A'}
$ python -c "print({'A', 'B'})"
{'A', 'B'}
the value of 'A'.__hash__())
changes each time on python 3