The last operation we will be looking at is the symmetric difference. We can think of this operation as the opposite of the intersection operation. A resulting set will include all elements from the sets which are in one or the other, but not both. In other words, elements that are unique to each set.
To perform this operation on the set
or frozenset
containers, we can use the .symmetric_difference()
method or the ^
operator. Like the other operators, the type of the first operand (a set
or frozenset
on the left side of the operator or method) determines if a set
or frozenset
is returned when finding the symmetric difference.
Take a look at the Venn diagram that represents a symmetric difference between set A
and set B
:
Here is what the symmetric difference looks like in Python:
# Given a set and frozenset of song tags for two python related hits prepare_to_py = {'rock', 'heavy metal', 'electric guitar', 'synth'} py_and_dry = frozenset({'classic', 'rock', 'electric guitar', 'rock and roll'}) # Find the elements which are exclusive to each song and not shared using the method exclusive_tags = prepare_to_py.symmetric_difference(py_and_dry) print(exclusive_tags)
Would output:
{'heavy metal', 'synth', 'rock and roll', 'classic'}
Alternatively, we can use the ^
operator:
# Find the elements which are exclusive to each song and not shared using the operator frozen_exclusive_tags = py_and_dry ^ prepare_to_py print(frozen_exclusive_tags)
Would output:
frozenset({'synth', 'rock and roll', 'heavy metal', 'classic'})
We can also update the original set
using this operation by using the .symmetric_difference_update()
method to update the original set
with the result instead of returning a new set
or frozenset
object.
Let’s create a symmetric difference in our music application!
Instructions
The users of our app would like to be able to see which tags are unique between them and their friends. This means that the tags which are not shared between the user and their friend are shown. In order to find this, we can use the symmetric difference.
First, create a set
called user_tags
.
Use a loop to populate the set to contain all of the tags from the songs in user_song_history
.
Next, repeat the same logic in order to collect all of the tags from the friend_song_history
and store it in a set
called friend_tags
.
Finally, find the unique tags by getting the symmetric difference between user_tags
and friend_tags
.
Store the result in a set
called unique_tags
and then print it!