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
?
Modifying a set in Python Sets are mutable. However, since they are unordered, indexing has no meaning. We cannot access or change an element of a set using indexing or slicing. Set data type does not support it.
The elements of the set are immutable, the set itself is mutable.
Though sets can't contain mutable objects, sets are mutable. But since they are unordered, indexing have no meaning. We cannot access or change an element of set using indexing or slicing. Set does not support it.
Set is an unordered and unindexed collection of items in Python. Unordered means when we display the elements of a set, it will come out in a random order. Unindexed means, we cannot access the elements of a set using the indexes like we can do in list and tuples.
>>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With