Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Comparing Sets

Sets are made for comparing. Anna and Tom are ordering a pizza together, and each of them has a set of the toppings they like:

anna = {"cheese", "ham", "mushrooms"}
tom = {"cheese", "salami", "mushrooms", "corn"}

print(anna & tom)
print(anna | tom)
print(anna - tom)
print(tom - anna)
{'mushrooms', 'cheese'}
{'salami', 'mushrooms', 'ham', 'corn', 'cheese'}
{'ham'}
{'salami', 'corn'}

Three operators compare two sets, and each of them gives a new set:

  • anna & tom (and) holds the values that are in both sets: the toppings both of them like.
  • anna | tom (or) holds the values that are in at least one of them, each once: everything that someone likes.
  • anna - tom (minus) holds the values of the first set that aren't in the second: what only Anna likes. Here the order matters: tom - anna is what only Tom likes.

The sets anna and tom themselves stay as they were. And the order of the values in each printed set can differ from run to run, as with any set of texts.

When no value is in both sets, the result is an empty set, which prints as set(): {"ham"} & {"corn"} is set().

The result is a set like any other, so len() and in work on it: len(anna | tom) is the number of all the toppings, 5.

Instructions

  1. 1

    Print who came on both days, with &: Both days: and the set. The output is Both days: {'Tom', 'Eva'}, or with the names the other way round. Keep the two lines with the sets: the exercise also tries other days.

  2. 2

    Print how many different people came during the week, with | and len(): People: 5.

  3. 3

    Finally, print who came on Monday but not on Thursday: Only Monday: and the set, {'Anna', 'Max'} in either order.

Back

9/11

  1. 1. Tuples
  2. 2. Unpacking
  3. 3. Quiz: Unpacking
  4. 4. Returning Several Values
  5. 5. A List of Tuples
  6. 6. Numbering with enumerate()
  7. 7. Sets
  8. 8. Adding to a Set
  9. 9. Comparing Sets
  10. 10. Quiz: Sets
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.