Are Python sets mutable?

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

    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.

提交回复
热议问题