A.difference(B) returns a new set containing elements in A that are not in B. The - operator provides the same set-to-set operation. Neither form changes A.
The method form can accept iterable arguments; operator forms require set-like operands. To change the original set, use difference_update(). See the Set operations overview for the full comparison.
All difference elements of first set A={1,2,3}
B={3,4,5}
print(A - B)
Output
{1,2}
A={1,2,3}
B={3,4,5}
x=A - B
print(type(x))
Output
<class 'set'>
A={'a','b','c'}
B={'a','y','z'}
print(A.difference(B))
Output
{'c', 'b'}
A={'a','b','c'}
B={'a','y','z'}
C={'a','b','l'}
print(A - B - C)
Output
{'c'}
A={'a','b','c','x','y'}
B='Alex'
print(A.difference(B))
Output
{'a', 'c', 'y', 'b'}
A={'a','b','c'}
B=['a','x','y']
print(A.difference(B))
Output
{'c', 'b'}
Below code will generate error.
print(A - B)
TypeError: unsupported operand type(s) for -: 'set' and 'list'
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.