2

This is the strange thing I noticed in Python sets. I read there is no order in sets, but it does pop lower elements from 0 till 79 and later from 79 till 127. It does not pop the lower ones any more. Only after 128 comes in 79 is popped. Why is it like this?

Is there any alternative where I can use the ordered data structure in Python? Why is it popping the lowest from 0 till 79 and not from 79 till 127?

>>s = set()
>>s.add(72)
>> s.add(74)
>> s.add(76)
>> s.pop()
72
>> s.add(79)
>> s.pop()
74
>> s.add(81)
>> s
set([81, 76, 79])
>> s.pop()
76
>> s.add(83)
>> s
set([81, 83, 79])
>> s.add(85)
>> s
set([81, 83, 85, 79])
>> s.pop()
81
>> s
set([83, 85, 79])
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
thanmai
  • 258
  • 3
  • 13
  • possible duplicate of [Does Python have an ordered set?](http://stackoverflow.com/questions/1653970/does-python-have-an-ordered-set) (or, possibly, http://stackoverflow.com/questions/10432022/in-python-is-set-pop-deterministic ) – Wooble Aug 17 '12 at 12:05
  • 2
    It's not a good idea to even _want_ to know the implementation behind behaviors like this, because they are absolutely not guaranteed or expected to be stable between versions *or* between implementations; if you're testing on CPython, you won't get the same behavior on IronPython or Jython, and there's no guarantee that the next CPython to come out will have the same behavior either. – Charles Duffy Aug 17 '12 at 13:18

2 Answers2

3

There is a "consistent" internal ordering depending on the insertion and removal of elements in dictionaries. See: http://docs.python.org/library/stdtypes.html#dict.items

As far as I'm aware sets use the same hashing implementation and will most likely have the same ordering effects.

Exelian
  • 5,749
  • 1
  • 30
  • 49
1

Why is it popping the lowest from 0 till 79 and not from 79 to 128 ?
Well no , the ordering is not random but it's completely arbitrary. There's is no specific ordering in python sets. Consider this :

>>> s.add(14)
>>> s.add(11)
>>> s.add(3)
>>> s.add(13)
>>> s.add(2)

>>> s.pop()
13
>>> s.pop()
14
>>> s.pop()
2
>>> s.pop()
3
>>> s.pop()
11

This isn't complying to your conclusion.( this time it happens for 14 )

SpiXel
  • 4,338
  • 1
  • 29
  • 45
  • >>> s = set() >>> s.add(14) >>> s.add(11) >>> s.add(3) >>> s.add(13) >>> s.add(2) >>> s set([3, 2, 11, 13, 14]) >>> s.pop() 3 >>> s.pop() 2 >>> s.pop() 11 >>> s.pop() 13 >>> s.pop() 14 >>> But i got this as the output. I was wrong about the output from 0 to 79. Thanks for the help. – thanmai Aug 20 '12 at 05:35