Python 3 reference · Set Methods
Python Set difference() Method
Return a new set with the elements of this set that are not in the others. The same as a - b.
Python 3 Since 3.0
Syntax
set.difference(*others)
Parameters
| Parameter | Description |
|---|---|
*others |
One or more iterables. |
Return value
A new set.
Examples
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a.difference(b)), sorted(a - b))
Output
[1, 2] [1, 2]
all_users = {"ada", "bob", "cy"}
active = ["bob"]
print(sorted(all_users.difference(active))) # any iterable works
Output
['ada', 'cy']
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
set.difference_update()· Remove from this set every element found in the others, in place. The same as a -= b.set.symmetric_difference()· Return a new set with elements in either set but not both. The same as a ^ b.set.intersection()· Return a new set with the elements common to this set and all others. The same as a & b.- Python Sets · tutorial