35 of 151 menu

The difference method

The difference method returns a set obtained from the elements by which the first set differs from the second. In the parameter, we specify the set with which we want to compare the original.

Syntax

set.difference(the set we want to compare with)

Example

Let's apply the difference method to get the different elements of two sets:

st1 = {'a', 'b', 'c'} st2 = {'e', 'g', 'a'} res = st1.difference(st2) print(res)

Result of code execution:

{'c', 'b'}

Example

The difference method also has a short form:

st1 = {'a', 'b', 'c'} st2 = {'e', 'g', 'a'} res = st1 - st2 print(res)

Result of code execution:

{'b', 'c'}

See also

  • method intersection,
    which returns the intersection of sets
  • method issubset,
    which checks the presence of elements of a set in a sequence
  • method issuperset,
    which checks the presence of elements of a sequence in a set
  • method symmetric_difference,
    which excludes common elements of a set and a sequence
byenru