Mahendra Vishwakarma Mahendra Vishwakarma - 1 year ago 69
Python Question

elements of sets in python must be mutable or immutable?

I was reading sets in python and got confusion that whether the elements of sets in python must be mutable or immutable? Because in the definition section they said "A set contains an unordered collection of unique and immutable objects." If it is true than how can a set contain the list as list is mutable?

Can someone clarify my doubt?

>>> x = [x for x in range(0,10,2)]
>>> x
[0, 2, 4, 6, 8] #This is a list x
>>> my_set = set(x) #Here we are passing list x to create a set
>>> my_set
set([0, 8, 2, 4, 6]) #and here my_set is a set which contain the list.

Answer Source

When you pass the set() constructor built-in any iterable, it builds a set out of the elements provided in the iterable. So when you pass set() a list, it creates a set containing the objects within the list - not a set containing the list itself, which is not permissible as you expect because lists are mutable.

So what matters is that the objects inside your list are immutable, which is true in the case of your linked tutorial as you have a list of (immutable) strings.

>>> set(["Perl", "Python", "Java"])
set[('Java', 'Python', 'Perl')]

Note that this printing formatting doesn't mean your set contains a list, it is just how sets are represented when printed. For instance, we can create a set from a tuple and it will be printed the same way.

>>> set((1,2,3))
set([1, 2, 3])

In Python 2, sets are printed as set([comma-separated-elements]).