Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Python sets mutable?

Tags:

python

set

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?

like image 816
Hubro Avatar asked Jan 07 '13 09:01

Hubro


People also ask

Why sets are mutable or immutable in Python?

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.

Is set a mutable object?

The elements of the set are immutable, the set itself is mutable.

Can a set contain mutable elements?

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.

Why set is unindexed in Python?

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.


1 Answers

>>>> 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.

like image 69
Tom van der Woerdt Avatar answered Sep 28 '22 04:09

Tom van der Woerdt