PythonDictionaries and sets
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
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 - otherParameters
#*others
sets or other collections
The collections whose elements will be subtracted.
More examples
#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']
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 - breturns what is inabut not inb. - A set difference loses order and duplicates. When those matter, filter the list instead:
[x for x in items if x not in blocked], whereblockedis a set.
Related entries
#- set.union()Returns a new set with the elements from every given set, without duplicates.
- set.intersection()Returns a new set with the elements that appear in every given set.
- set.discard()Removes an element from a set if it's there. A missing element causes no error.
- List comprehensionsA concise way to build lists, sets, and dictionaries from other collections.
Spotted a mistake or missing an example? Write to us.