set.difference()

Returns a new set with the elements of the first set that are not in the others.

Returns
A new set.
Changes the original
No
On this page

Example

#
Python
module_tasks = {"1_1", "1_2", "1_3", "1_4", "1_5"}
done = {"1_1", "1_3"}

todo = module_tasks.difference(done)
print(sorted(todo))
print(sorted(done - module_tasks))
Resultsaved result, you can check it
['1_2', '1_4', '1_5']
[]

Definition and usage

#

The difference() method returns the difference of sets: the elements of the set you call it on, minus everything that appears in the given collections. Order matters, because a - b is usually something different from b - a.

The - operator gives the same result for two sets. The method also accepts lists and other collections, and several arguments at once.

A related operation is the symmetric difference, the symmetric_difference() method or the ^ operator. It returns the elements that belong to exactly one of the two sets. The in-place versions are difference_update() and -=.

Syntax

#
Syntax
set.difference(*others)
set - other

Parameters

#
  • *others

    sets or other collections

    The collections whose elements will be subtracted.

More examples

#
Plain and symmetric difference
Python
emma = {"HTML", "CSS", "Python"}
jack = {"Python", "React"}

print(sorted(emma - jack))
print(sorted(jack - emma))
print(sorted(emma ^ jack))
Resultsaved result, you can check it
['CSS', 'HTML']
['React']
['CSS', 'HTML', 'React']
Subtracting a list from a set
Python
words = ["python", "and", "lists", "with", "python", "sets"]
stop_words = ["and", "with", "plus"]

print(sorted(set(words).difference(stop_words)))
Resultsaved result, you can check it
['lists', 'python', 'sets']

Good practices

#
  • Remember the order: a - b returns what is in a but not in b.
  • A set difference loses order and duplicates. When those matter, filter the list instead: [x for x in items if x not in blocked], where blocked is a set.

Related entries

#

Spotted a mistake or missing an example? Write to us.