Are Python sets mutable?

前端 未结 8 1931
渐次进展
渐次进展 2021-01-31 09:14

Are sets in Python mutable?


In other words, if I do this:

x = set([1, 2, 3])
y = x

y |= set([4, 5, 6])

Are x and

相关标签:
8条回答
  • 2021-01-31 09:51

    Your two questions are different.

    Are Python sets mutable?

    Yes: "mutable" means that you can change the object. For example, integers are not mutable: you cannot change the number 1 to mean anything else. You can, however, add elements to a set, which mutates it.

    Does y = x; y |= {1,2,3} change x?

    Yes. The code y = x means "bind the name y to mean the same object that the name x currently represents". The code y |= {1,2,3} calls the magic method y.__ior__({1,2,3}) under the hood, which mutates the object represented by the name y. Since this is the same object as is represented by x, you should expect the set to change.


    You can check whether two names point to precisely the same object using the is operator: x is y just if the objects represented by the names x and y are the same object.

    If you want to copy an object, the usual syntax is y = x.copy() or y = set(x). This is only a shallow copy, however: although it copies the set object, the members of said object are not copied. If you want a deepcopy, use copy.deepcopy(x).

    0 讨论(0)
  • 2021-01-31 09:51

    Yes, Python sets are mutable because we can add, delete elements into set, but sets can't contain mutable items into itself. Like the below code will give an error:

    s = set([[1,2,3],[4,5,6]])
    

    So sets are mutable but can't contain mutable items, because set internally uses hashtable to store its elements so for that set elements need to be hashable. But mutable elements like list are not hashable.

    Note:
    Mutable elements are not hashable
    Immutable elements are hashable

    Just like key of a dictionary can't be a list.

    0 讨论(0)
提交回复
热议问题