The intersection of two sets A and B is the set containing all the elements that A and B have in common. It is represented as A ⋂ B. If the two sets have nothing in common, then the answer is the empty set.

Let us try to find the intersection of the set of all prime numbers and even numbers. A prime number has only two factors: 1 and itself. The set of prime numbers, P, is {2, 3, 5, 7, 11, 13, …}.

To find P ⋂ E (the set of even numbers), or all even primes, list the elements present in both E and P. The number 2 is the only even prime number, so E ⋂ P = {2}.

Let us look at another example. A set of band students, B = {Sam, Chen, Halona, Paul} and a set of chorus students, C = {Halona, Hope, Leena, Paul, Tony, Zach} have a performance tomorrow. Which band students are part of the chorus too?

We need to look for students in the band who are part of both band and chorus (set intersection).

B ⋂ C = {Halona, Paul}


The union of two sets A and B is the set of all their elements together (without repeating any elements that they share). It is represented as A ∪ B. Let us try to find the list of all students who are participating in the concert, as part of band or chorus (set union).

B ∪ C = {Sam, Chen, Halona, Paul, Hope, Leena, Tony, Zach}


The difference between two sets A, B is represented as A - B and is the set of all elements of A that are not present in B. An ice cream website held a poll asking users which flavor they liked the best. Here are the results from North Dakota and South Dakota:

N = {Chocolate, Vanilla, Strawberry, Banana-Chocolate-Chip}

S = {Chocolate, Vanilla, Butter-Pecan, Cappuccino, Cherry-Almond}

We can use the difference operator to find the flavors that are popular in North Dakota, but not in South Dakota.

N - S = {Strawberry, Banana-Chocolate-Chip}

The .union() method of Python can be used to find the union of one set with another. The .intersection() method returns the intersection of one set with another.



Write code in Python to create these sets:

  • The set of herbivores, H = {rabbit, elephant, panda, elk, goat}
  • The set of pets, P = {cat, dog, rabbit, snake, goat}

Write code to print the list of herbivores that can be kept as pets.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?