Spring Deals - hours only!Up to 70% off on all courses and bundles.-Close
Set basics
Relationships between sets
13. The difference() and symmetric_difference() functions


Very well done! There are two more functions that create a new set from a relationship. One of them is difference():

kate_fav_movies = {'Halloween', 'A Star Is Born', 'Hocus Pocus'}
alan_fav_movies = {'A Star Is Born', 'The Lion King', 'Harry Potter'}

kate_unique_movies = kate_fav_movies.difference(alan_fav_movies)
print('Kate has the following movies that Alan doesn\'t have:', kate_unique_movies)

Notice that kate_unique_movies contains all movies from kate_fav_movies that are not present in alan_fav_movies. difference() is not symmetrical – the two lines below yield different results:


You can see the results for both invocations in the picture below:

Alternatively, you can use the following notation:

kate_fav_movies - alan_fav_movies
alan_fav_movies - kate_fav_movies

The symmetric_difference() function returns those elements that are present in either set, but not in both sets. Here is how it works:

The syntax is comparable to that of difference() ...


... and you can also use a slightly different abbreviated form:

kate_fav_movies ^ alan_fav_movies


Use the symmetric_difference() function to solve the following problem:

You are again given data for employees in cities A and B; some of these employees work in both cities. Your task is to find all employees that only work in a single location and print the following:

These employees only work in a single location:
1. {name1}
2. {name2}

Stuck? Here's a hint!

In your solution, use: