pythonset

Are Python sets mutable?


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 y still pointing to the same object, or was a new set created and assigned to y?


Solution

  • >>>> 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])
    
    set1 = {1,2,3}
    
    set2 = {1,2,[1,2]}  --> unhashable type: 'list'
    # Set elements should be immutable.
    

    Conclusion: sets are mutable.