Post

Python Set difference() Method

In this tutorial, we will understand about the python set difference() method and its uses.

Python Set difference() Method

The Python set difference() method returns a new set containing elements that exist in the first set but not in the second set. It can also be written using the minus operator (-). The original sets remain unchanged.

The syntax of the difference() method is:

1
2
3
set.difference(set2)
# or
set1 - set2

Python set difference() Parameters

The difference() method takes one parameter:

  • set2: Another set, or any iterable (list, tuple, etc.) whose elements will be removed from the first set.

Here are examples demonstrating the difference() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Example 1: Basic set difference
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
result = set1.difference(set2)
print(result)  # Output: {1, 2, 3}

# Example 2: Using operator syntax
numbers1 = {1, 2, 3, 4}
numbers2 = {3, 4, 5, 6}
result = numbers1 - numbers2
print(result)  # Output: {1, 2}

# Example 3: Multiple set difference
set1 = {1, 2, 3, 4}
set2 = {2, 4}
set3 = {3}
result = set1.difference(set2, set3)
print(result)  # Output: {1}

The difference() method is particularly useful when you need to find elements that are unique to one set.

Khushal Jethava
Khushal Jethava

Machine Learning Engineer at Codiste, specializing in Generative AI, NLP, and Computer Vision. Building production AI systems with Python.

This post is licensed under CC BY 4.0 by the author.