difference

set.difference

Returns a NEW set with elements from s that are NOT in any of the arguments. Method form takes iterables; - requires sets.

s.difference(*others)  |  s - other

Parameters

Parameter Purpose
*others Iterables or sets whose elements are subtracted from s
returns A new set — s is unchanged

Examples

>>> {1, 2, 3, 4} - {2, 4}
{1, 3}

Subtracts elements found in the right-hand set.

>>> {1, 2, 3}.difference([2], [3])
{1}

Multiple iterables are all subtracted.

>>> {1, 2} - {3, 4}
{1, 2}

No overlap — result equals the left set.

>>> a = {1, 2}; b = {2, 3}
>>> a - b == b - a
False

Difference is NOT commutative; a-b keeps only a's exclusives.

Gotcha

Difference is asymmetric: a - b keeps elements only in a. For elements in either but not both, use symmetric_difference (^).

Related methods

← All Python set methods · List methods · list vs tuple vs set