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

ParameterDescription
*others One or more iterables.

Return value

A new set.

Examples

Elements only in aTry it yourself
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a.difference(b)), sorted(a - b))

Output

[1, 2] [1, 2]
Works with any iterableTry it yourself
all_users = {"ada", "bob", "cy"}
active = ["bob"]
print(sorted(all_users.difference(active)))  # any iterable works

Output

['ada', 'cy']

Version history

VersionChange
Python 3.0Added