1

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?

sophros
  • 14,672
  • 11
  • 46
  • 75
TXT
  • 11
  • 1
  • 1
    ``set.update`` is an inplace operation, like ``list.append``. These always return ``None`` in Python. – MisterMiyagi Jun 15 '21 at 06:39
  • Does this answer your question? [Why does “return list.sort()” return None, not the list?](https://stackoverflow.com/questions/7301110/why-does-return-list-sort-return-none-not-the-list) – MisterMiyagi Jun 15 '21 at 06:40
  • I have got your point, many thanks @MisterMiyagi – TXT Jun 15 '21 at 06:43

2 Answers2

0

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.

sophros
  • 14,672
  • 11
  • 46
  • 75
0

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))
hari hara
  • 41
  • 1
  • 10