'order' of unordered Python sets

前端 未结 5 2128
暗喜
暗喜 2020-11-22 13:03

I understand that sets in Python are unordered, but I\'m curious about the \'order\' they\'re displayed in, as it seems to be consistent. They seem to be out-of-order in the

5条回答
  •  名媛妹妹
    2020-11-22 14:01

    The reason of such behavior is than Python use hash tables for dictionary implementation: https://en.wikipedia.org/wiki/Hash_table#Open_addressing

    Position of the key is defined by it's memory address. If you know Python reuse memory for some objects:

    >>> a = 'Hello world'
    >>> id(a)
    140058096568768
    >>> a = 'Hello world'
    >>> id(a)
    140058096568480
    

    You can see that object a has different address every time it's init.

    But for small integers it isn't change:

    >>> a = 1
    >>> id(a)
    40060856
    >>> a = 1
    >>> id(a)
    40060856
    

    Even if we create second object with different name it would be the same:

    >>> b = 1
    >>> id(b)
    40060856
    

    This approach allow to save memory which Python interpreter consume.

提交回复
热议问题