Python Set - symmetric_difference() Method

The Python symmetric_difference() method returns a set which contains all elements which are either in first set or second set but not in both. This method takes only argument and can take a set or an iterable as an argument. Please note that, this method does not change the original set.

The below figure depicts two sets called A = {10, 20, 30, 40, 50, 60} and B = {40, 50, 60, 70}. As 40, 50 and 60 are common elements between A and B, hence intersection of these sets will be {40, 50, 60}. Similarly, union of these two sets will be {10, 20, 30, 40, 50, 60, 70}. The symmetric_difference() method can be expressed as:

• A.symmetric_difference(B) is same as (AUB) - (AꓵB) = {10, 20, 30, 70}
• B.symmetric_difference(A) is same as (BUA) - (BꓵA) = {10, 20, 30, 70}

Syntax

```set.symmetric_difference(iterable)
```

Parameters

 `iterable` `Required. `specify set or iterable to compute symmetric_difference set.

Return Value

Returns a set which contains all elements which are either in first set or second set but not in both.

Example: Symmetric difference set using set as an argument

In the example below, two sets called SetA and SetB are taken to compute Symmetric difference set using symmetric_difference() method.

```SetA = {10, 20, 30, 40, 50, 60}
SetB = {40, 50, 60, 70}

print(SetA.symmetric_difference(SetB))
```

The output of the above code will be:

```{70, 10, 20, 30}
```

Example: Symmetric difference set using iterable as an argument

In the example below, a set called SetA and list called ListB are taken to compute Symmetric difference set using symmetric_difference() method.

```SetA = {10, 20, 30, 40, 50, 60}
ListB = [40, 50, 50, 60, 60, 70]

print(SetA.symmetric_difference(ListB))
```

The output of the above code will be:

```{70, 10, 20, 30}
```

❮ Python Set Methods

5