Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python set won't perform union

I have a class with a member that is defined:

self.myset = set()

When I perform myobject.myset.add('item'), using an instance of my class, it works fine: print(myobject.myset) gives me {'item'} .

However, when I perform myobject.myset.union(yourset), where yourset is not empty, it won't work; print(myobject.myset) still prints as an empty set. Why is one method (add) working while another (union) is quietly (no exception thrown) failing? Even myobject.myset = yourset works, but union in particular won't.

I'm using Python 3.

like image 387
mwarrior Avatar asked Jul 17 '26 07:07

mwarrior


2 Answers

set.union() does not modify the old set in-place, but set.add() does. set.union() returns a new set instead.

myobject.myset = myobject.myset.union(yourset)

This should do the trick. See the Python documentation on set.union() for more information.

like image 105
piglei Avatar answered Jul 18 '26 20:07

piglei


union doesn't modify the set - it returns a new set. This is clearer if you use the operators for union and intersection - a.union(b) and a | b do the same thing (except that the method form can take the union of three or more sets without creating extra temporary objects). For an in place union, you can use the update method or the equivalent (for two sets) form a |= b.

like image 27
lvc Avatar answered Jul 18 '26 21:07

lvc