FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Set difference() method with examples




The difference() method in Python returns the difference between two given sets. Lets say we have two sets A and B, the difference between A and B is denoted by A-B and it contains the elements that are in Set A but in Set B.

How the difference is calculated between two sets?

Lets say we have two Sets X and Y as follows:
X = {"hello", 2, 5}
Y = {2, 9, "bye"}

Difference between two sets is denoted by - sign.
Elements that are in Set X but not in Set Y
X-Y = {"hello", 5}

Elements that are in Set Y but not in Set X
Y-X = {9, "bye"}

Python Set difference() method Syntax

X.difference(Y)

This is equivalent to X-Y.
Parameters: This method takes a Set as parameter.
Return Value: It returns a Set that is a difference between two sets. For example X.difference(Y) would return a Set that contains the elements that are in Set X but not in Set Y.

Python Set difference() method Example

In the following example we have two sets X and Y. We are finding the difference between X & Y and Y & X using the difference() method.

# Set X
X = {"hello", 9, 10, "hi"}

# Set Y
Y = {9, "hi", 6, "noidatut"}

# Equivalent to X - Y
print("X-Y is:",X.difference(Y))

# Equivalent to Y - X
print("Y-X is:",Y.difference(X))

Difference between Sets using - Operator

We can use the - operator on Sets. This works same as difference() method. Lets take the same example that we have seen above using - operator.

# Set X
X = {"hello", 9, 10, "hi"}

# Set Y
Y = {9, "hi", 6, "noidatut"}

# Equivalent to X.difference(Y)
print("X-Y is:",X-Y)

# Equivalent to Y.difference(X)
print("Y-X is:",Y-X)

Output

X-Y is: {10, 'hello'}
Y-X is: {'noidatut', 6}







Leave Comment