Good job! Now that we know how to handle single sets, let's move on to defining the relationships between two sets. The two sets below store Kate's favorite movies and Alan's favorite movies. We want to find out if they have any favorite movies in common:
kate_fav_movies = {'Halloween', 'A Star Is Born', 'Hocus Pocus'}
alan_fav_movies = {'A Star Is Born', 'The Lion King', 'Harry Potter'}
common_fav_movies = kate_fav_movies.intersection(alan_fav_movies)
print('Alan\'s and Kate\'s common favorite movies are:', common_fav_movies)
To find Kate and Alan's common favorite movies, we used the intersection()
method. It returns those elements that are present in both sets:
Note that both lines below provide the same result, which is a new set:
kate_fav_movies.intersection(alan_fav_movies)
alan_fav_movies.intersection(kate_fav_movies)
If you feel that's a lot of typing, you can use the equivalent syntax:
kate_fav_movies & alan_fav_movies