Python Set difference() Method

Example

Return a set containing items that exist only in set x and not in set y:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y) 
print(z)

Run Instance

Definition and Usage

The different() method returns a set containing the differences between two sets.

Meaning: The returned set contains items that exist only in the first set and do not exist in both sets.

Syntax

set.difference(set)

Parameter Values

Parameters Description set Required. To check the items that differ.

More Examples

Example

Reverse the first example. Return a set containing items that exist only in set y and not in set x:

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = y.difference(x) 
print(z)

Run Instance