Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.symmetric_difference() method

Reference for Python set.symmetric_difference(): elements in exactly one of two sets, the ^ operator, the in-place update variant and chaining several sets.

The symmetric_difference() method returns a new set with the elements that are in either the set or the other collection, but not in both. Think of it as "union minus intersection", or an exclusive-or for sets.

The operator form is a ^ b. The in-place variant is symmetric_difference_update(), or a ^= b.

Python
{1, 2, 3}.symmetric_difference({3, 4})   # {1, 2, 4}

Try it

Python What changed between two lists?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Iterables, operators and update

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
set.symmetric_difference(other)
set ^ other
set.symmetric_difference_update(other)
set ^= other
Name Description
other An iterable (method) or a set/frozenset (operator). Items must be hashable.

Return value: a new set for symmetric_difference() and ^. The update forms change the set in place and return None.

Raises: TypeError if other is not iterable (method), is not a set (operator), or has unhashable items.

Usage notes

  • Takes exactly one argument. Unlike union() and intersection(), the method does not accept several sets. Chain it: a ^ b ^ c.
  • Chaining is not "in exactly one". With three sets, a ^ b ^ c keeps elements that appear in an odd number of the sets (1 or 3), because the operation is associative.
  • Symmetric. a ^ b equals b ^ a.
  • Equal sets give an empty result, and disjoint sets give their union.
  • Equivalent forms: (a - b) | (b - a) and (a | b) - (a & b).
  • Result type follows the left operand for set and frozenset: frozenset ^ set returns a frozenset.
  • The new set is a copy; the originals are untouched unless you use the update forms.