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

Instruction

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:

kate_fav_movies.difference(alan_fav_movies)
alan_fav_movies.difference(kate_fav_movies)

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() ...

kate_fav_movies.symmetric_difference(alan_fav_movies)

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

kate_fav_movies ^ alan_fav_movies

Exercise

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:

city_a_employees.symmetric_difference(city_b_employees)