Are Python sets mutable?

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

    Sets are muttable

    s = {2,3,4,5,6}
    type(s)
    <class 'set'>
    s.add(9)
    s
    {2, 3, 4, 5, 6, 9}
    

    We are able to change elements of set

    0 讨论(0)
  • 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.

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

    After changing the set, even their object references match. I don't know why that textbook says sets are immutable.

        >>> s1 ={1,2,3}
        >>> id(s1)
        140061513171016
        >>> s1|={5,6,7}
        >>> s1
        {1, 2, 3, 5, 6, 7}
        >>> id(s1)
        140061513171016
    
    0 讨论(0)
  • 2021-01-31 09:40

    I don't think Python sets are mutable as mentioned clearly in book "Learning Python 5th Edition by Mark Lutz - Oreilly Publications"

    0 讨论(0)
  • 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)
    <class 'set'>
    

    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.

    0 讨论(0)
  • 2021-01-31 09:44
    print x,y
    

    and you see they both point to the same set:

    set([1, 2, 3, 4, 5, 6]) set([1, 2, 3, 4, 5, 6])
    
    0 讨论(0)
提交回复
热议问题