Can I use update method of set in Python to merge two set (x-y) and (y-x)?

172 Views Asked by At

I have these two source code and I do not understand the difference

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x.symmetric_difference(y)

print(z) ## z now is {'google', 'cherry', 'microsoft', 'banana'}

and

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = (x - y).update((y - x))

print(z) ## z now is NoneType

why the second code does not result in as the first one? as I know, (x-y) will return a set, then I apply update method with (y - x) to merge (x-y) set and (y-x), so the results should be same?

2

There are 2 best solutions below

1
On

With a small change it will work:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

z = x - y
z.update((y - x))

print(z)

{'google', 'cherry', 'microsoft', 'banana'}

Update operation is in-place, so for the expression you use x-y ends up being temporary set value which is updated in-place. Therefore, assignment ends up being None.

0
On

As @MisterMiyagi said, The update function is in place operation. You can save (x - y) in some variable and you can perform the update operation. Something like this.

var = (x - y)
var.update((y - x))