-2

Can anyone explain to me why :

p = {-1,2,-3}
print(p)

will print

{2, -3, -1}

and when I convert to list

pa = list(p)
print(pa)

I will get

[2, -3, -1]

How can I convert p to a list with the same order of items

[-1, 2, -3]

PS: this happens only when I am using negative items

martineau
  • 119,623
  • 25
  • 170
  • 301
H.D.
  • 1
  • 2
    sets are not ordered. In a word: you cannot preserve order unless you stored the order ... – Jean-François Fabre Oct 03 '16 at 22:09
  • Seemingly-odd things happen around this with small integers because they hash to their own values, so are often (but not always) kept in sorted order. But you should not rely on dictionary or set order. – jonrsharpe Oct 03 '16 at 22:11
  • Thank you for your prompt reply. I know already that sets are immutable. But I don't have a choice. I am getting a set from a method. I have to convert it to a list (while keeping the same order) in order to feed it to another method. Any help !! – H.D. Oct 03 '16 at 22:24
  • Sets are are **not immutable**. They are **unordered**. There is no order to keep. – juanpa.arrivillaga Oct 03 '16 at 22:27

1 Answers1

0

set in python are unordered. In case you want to maintain the order of elements, use collections.OrderedDict.fromkeys() instead. This will also behave as a set. For example:

>>> import collections
>>> p = collections.OrderedDict.fromkeys([-1,2,-3])
>>> print(p)
OrderedDict([(-1, None), (2, None), (-3, None)])
>>> p = collections.OrderedDict.fromkeys([-1,2,-3,2]) # <-- 2 repeated twice
>>> print(p)  # <-- Removed duplicated entry of '2', same as set
OrderedDict([(-1, None), (2, None), (-3, None)])
>>> l = list(p)
>>> print(l)  # <-- order is maintained
[-1, 2, -3]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • Sorry but it doesn't work because fromkeys does not take sets as parameter – H.D. Oct 03 '16 at 22:30
  • You need to replace the code where your initializing `set` to `collections.OrderedDict.fromkeys()`. Once you have created the set, there is no way you could extract the original order from it. – Moinuddin Quadri Oct 03 '16 at 22:36
  • I have to find a another way around. But thank you anyway. – H.D. Oct 03 '16 at 23:49