Are Python sets mutable?

前端 未结 8 1933
渐次进展
渐次进展 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:39

    >>>> x = set([1, 2, 3])
    >>>> y = x
    >>>> 
    >>>> y |= set([4, 5, 6])
    
    >>>> print x
    set([1, 2, 3, 4, 5, 6])
    >>>> print y
    set([1, 2, 3, 4, 5, 6])
    
    • Sets are unordered.
    • Set elements are unique. Duplicate elements are not allowed.
    • A set itself may be modified, but the elements contained in the set must be of an immutable type.
    set1 = {1,2,3}
    
    set2 = {1,2,[1,2]}  --> unhashable type: 'list'
    # Set elements should be immutable.
    

    Conclusion: sets are mutable.

提交回复
热议问题