简体   繁体   中英

elements of sets in python must be mutable or immutable?

I was reading sets in python http://www.python-course.eu/sets_frozensets.php 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.
>>> 

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

You seem to be confusing initialising a set with a list:

a = set([1, 2])

with adding a list to an existing set:

a = set()
a.add([1, 2])

the latter will throw an error, where the former initialises the set with the values from the list you provide as an argument. What is most likely the cause for the confusion is that when you print a from the first example it looks like:

set([1, 2])

again, but here [1, 2] is not a list, just the way a is represented:

a = set()
a.add(1)
a.add(2)
print(a)

gives:

set([1, 2])

without you ever specifying a list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM