Are Python sets mutable?

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

    Python sets are classified into two types. Mutable and immutable. A set created with 'set' is mutable while the one created with 'frozenset' is immutable.

    >>> s = set(list('hello'))
    >>> type(s)
    
    

    The following methods are for mutable sets.

    s.add(item) -- Adds item to s. Has no effect if listis already in s.

    s.clear() -- Removes all items from s.

    s.difference_update(t) -- Removes all the items from s that are also in t.

    s.discard(item) -- Removes item from s. If item is not a member of s, nothing happens.

    All these operations modify the set s in place. The parameter t can be any object that supports iteration.

提交回复
热议问题