Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

set.difference

Creates a set containing members of the first set absent from the other input.

Version: Python 3.14; repository image, production runtime not attested

Syntax

s.difference(*others)

Creates a set containing members of the first set absent from the other input.

The method accepts an iterable and leaves the original set intact.

Each iterable supplies exclusions. Of 2 and 3, only 2 is absent from [3, 4]. The result is a new set; sorted builds a list solely for reproducible display. Additional iterables exclude their members as well.

s = {1, 2, 3}
assert s.difference([2], [3]) == {1} and s == {1, 2, 3}

Examples

s = {2, 3}
print(sorted(s.difference([3, 4])))
print(sorted(s))

Result

[2]
[2, 3]

Each iterable supplies exclusions. Of 2 and 3, only 2 is absent from [3, 4]. The result is a new set; sorted builds a list solely for reproducible display. Additional iterables exclude their members as well.

Sources