0

If the two set I have are:

animals = { "human", "gorilla", "fish", "parrot", "kangaroo" }
mammals = { "gorilla", "human", "kangaroo" }

What Python code could I use that would show me animals that are also mammals?

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • 1
    Does this answer your question? [Best way to find the intersection of multiple sets?](https://stackoverflow.com/questions/2541752/best-way-to-find-the-intersection-of-multiple-sets) – TheFungusAmongUs Jul 29 '22 at 01:38
  • 1
    Welcome to Stack Overflow. As general advice for asking questions (as well as for [doing your own research](https://meta.stackoverflow.com/questions/261592), it's important to think *as clearly as possible* about what you *actually want* before posting. Displaying a set is trivial; the question is really about how to *compute* the subset that you want. Since you are apparently familiar with sets, the next step is to figure out the *name* of the kind of subset you are trying to create. Here, that is evidently an *intersection* of the two sets; knowing this makes searching much easier. – Karl Knechtel Jul 29 '22 at 01:49

2 Answers2

0

You can use python's intersection like this:

animals = { "human", "gorilla", "fish", "parrot", "kangaroo" }
mammals = { "gorilla", "human", "kangaroo" }

# Print mammals that are also animals
print(mammals.intersection(animals))
Gabriel Deml
  • 164
  • 2
  • 6
0

using the corresponding method:

animals.intersection(mammals)

using the shorthand for the method:

animals & mammals

both return the intersection (animals that are also mammals), so if you want to show it to the terminal you just print out the return value

print(animals & mammals)
Magmurrr
  • 238
  • 1
  • 9