symmetric_difference(other) builds a new set with the items that are in exactly one of the two collections: in the set or in other, but not in both. Neither original is changed.
Think of it as everything that differs between two groups. It equals the union minus the intersection, and it gives the same answer whichever side you start from.
set.symmetric_difference() is an instance method of the built-in set type: call it on a set with dot notation, such as last_week.symmetric_difference(...). No import is needed.
Syntax
Pass exactly one iterable, and keep the returned set in a variable.
python
changed = s.symmetric_difference(iterable)
changed = s ^ other_set
Call
What it does
{1, 2, 3}.symmetric_difference({3, 4})
Returns {1, 2, 4}: 3 is in both, so it is left out.
{1, 2}.symmetric_difference([2, 3])
Returns {1, 3}: any iterable works as the argument.
{1, 2}.symmetric_difference({1}, {2})
Raises TypeError: the method takes exactly one argument.
a ^ b is a shortcut for a.symmetric_difference(b), but only between two sets. To change the existing set instead, use symmetric_difference_update().
Method signatures
python
set.symmetric_difference(other)
# returns: a new set with the items in exactly one of the set and other
# raises: TypeError unless exactly one iterable is given
Parameters
Parameter
Description
other
One iterable: set, list, tuple, string, and so on. Unlike union() and intersection(), you cannot pass several; chain calls or operators instead.
Return Value
Return Value
Description
set
A new set with the items present in only one side. It is empty (set()) when the two collections hold the same items.
Python Examples
Example 1 — Spot What Changed Between Two Schedules
Find the activities that were dropped or added, and split them with the plain difference.
4
['c1', 'c7'] ['c4', 'c5']
only one argument is allowed
How It Works
Four ids disagree. c2 and c3 exist in both systems, so c1, c7, c4, and c5 are the mismatches.
Split by side. Intersecting the mismatches with billing gives c1 and c7; subtracting billing leaves c4 and c5.
Two arguments are rejected.symmetric_difference() accepts only one iterable, so the call raises TypeError, which the except block catches.
Frequently Asked Questions
A new set with the items that are in exactly one of the two collections, which means items found in both are left out. The originals are not changed.
Yes for two sets, but the ^ operator needs sets on both sides. The method also accepts a list, tuple, or string as its argument.
difference() keeps only the items from the first set that are missing from the second. symmetric_difference() keeps the unshared items from both sides.
No. It takes exactly one argument and raises TypeError otherwise. Chain the operator instead, as in a ^ b ^ c.
Use symmetric_difference_update() or the ^= operator. They update the original set and return None.