Python Set - difference method

The difference method returns a set of elements which are present in one set and not present in the another

Set Updated 16 Sep 2016 1 min read

Method signature

difference(anotherSetObject_in)

Overview

A difference set is returned - containing elements in this set which are not in the other set.

Parameters

anotherSetObject_in : The set to be compared to produce the difference set.

Example

python
# Example Python program that finds the difference between

            # two Python sets

            s1 = {1,2,3,4,5}

            s2 = {5,6,7}

# Returns the set of elements that are not present in the set s2

            diff1 = s1.difference(s2)

            print(diff1)

# Returns the set of elements that are not present in the set s1

            diff2 = s2.difference(s1)

            print(diff2)

Output

Output
{1, 2, 3, 4}

{6, 7}