Python Set difference() (original) (raw)

Last Updated : 18 Apr, 2026

The set.difference() method in Python returns a new set containing elements that are present in the first set but not in the other given set(s). It performs set subtraction and removes all common elements. The original sets remain unchanged.

420851440

Difference between two sets

**Example: In this example, elements that are present in one set but not in another are found using difference().

Python `

a = {10, 20, 30, 40, 80} b = {100, 30, 80, 40, 60} print(a.difference(b)) print(b.difference(a))

`

**Explanation:

Syntax

set1.difference(set2, set3, ...)

Examples

**Example 1: In this example, the difference is calculated using multiple sets.

Python `

a = {1, 2, 3, 4, 5} b = {3, 4, 5, 6, 7} c = {5, 6, 7, 8, 9} print(a.difference(b, c))

`

**Explanation: a.difference(b, c) removes elements found in b or c, only elements unique to a remain.

**Example 2: Here, the difference of a set with an empty set is demonstrated.

Python `

a = {10, 20, 30, 40} b = set() print(a.difference(b))

`

**Explanation: a.difference(b) removes elements of b from a. Since b is empty, a remains unchanged.

**Example 3: In this example, the difference operation is performed when one set is a subset of another.

Python `

a = {10, 20, 30, 40, 80} b = {10, 20, 30, 40, 80, 100} print(a.difference(b))

`

**Explanation: