Learn

Let’s say that we have two or more sets, and we want to find which items both sets have in common. The set container has a method called .intersection() which returns a new set or frozenset consisting of those elements. An intersection can also be performed on multiple sets using the & operator.

Similar to the other operations, 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 intersection.

Take a look at the Venn diagram representing an intersection of set A and set B:

Python Set Intersection

Here is what an intersection 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 intersection between them while providing the `frozenset` first. frozen_intersected_tags = py_and_dry.intersection(prepare_to_py) print(frozen_intersected_tags)

Would output:

frozenset({'electric guitar', 'rock'})

And here it is with the & operator:

# Find the intersection using the operator `&` and providing the normal set first intersected_tags = prepare_to_py & py_and_dry print(intersected_tags)

Would output:

{'rock', 'electric guitar'}

In addition to a regular intersection, the set container can also use a method called .intersection_update(). Instead of returning a new set, the original set is updated to contain the result of the intersection.

Let’s see how we can use the intersection operation to create a recommendation feature for our music application!

Instructions

1.

We want to add a feature to our app which will recommend songs based on the most recent songs a user has listened to. One way we can do this is by using the intersection of the recent song tags. Let’s use the intersection of these tags to find which other songs are similar.

First, create a variable called tags_int that stores the intersection between the tags for the user_recent_songs two recent songs 'Retro Words' and 'Lowkey Space'. Remember to convert each list into a set to perform the operation.

We will be using these common tags as a basis for finding a recommended song in song_data.

2.

Now, let’s find the recommended songs based on the common tags we found in the previous step.

Find all other songs in song_data which have these tags. Store the songs which have any matching tags into a dictionary called recommended_songs. Make sure that you do not add any songs which the user has listened to recently!

Print recommended_songs to see the result!

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?