Can 'symmetric_different_update' work with list that was converted to a set?

Viewed 22

I have a problem when writing code with symmetric_different_update:

morning = ['Java', 'C', 'Ruby', 'Lisp', 'C#']
afternoon = ['Python', 'C#', 'Java', 'C', 'Ruby']
set(afternoon).symmetric_difference_update(morning)
print(set(afternoon))

My output:

{'Java', 'Python', 'C', 'C#', 'Ruby'}

In the case morning and afternoon are sets, its work normally

1 Answers

If morning and afternoon are sets, it also doesn't work:

>>> morning = {'Java', 'C', 'Ruby', 'Lisp', 'C#'}
>>> afternoon = {'Python', 'C#', 'Java', 'C', 'Ruby'}
>>> set(afternoon).symmetric_difference_update(morning)
>>> print(set(afternoon))
{'Java', 'Python', 'Ruby', 'C#', 'C'}

The problem comes from the fact that you call the method on a copy of the set/list. To fix this, you could not use the _update variant and assign back to the same name:

>>> morning = ['Java', 'C', 'Ruby', 'Lisp', 'C#']
>>> afternoon = ['Python', 'C#', 'Java', 'C', 'Ruby']
>>> afternoon = list(set(afternoon).symmetric_difference(morning))
>>> print(afternoon)
['Lisp', 'Python']
Related