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

Sets

A list can hold the same value many times. Sometimes you only want to know which values there are, each of them once: which kinds of pets the students in a class have, or who visited a website. For that, Python has sets. A set is written in curly braces, like a dictionary, but it holds single values instead of pairs:

pets = {"dog", "cat", "dog", "fish", "cat"}
print(pets)
print(len(pets))
{'cat', 'fish', 'dog'}
3

Each value is in a set only once, as each key is in a dictionary only once. The second "dog" and the second "cat" were left out, so len() counts the different values: 3.

And a set has no order. It doesn't remember the order in which you wrote the values, so it has no indexes either: pets[0] ends with TypeError: 'set' object is not subscriptable (it can't be read with square brackets). When you print a set of texts, the order can even change from one run to the next. The output above is from one run; another run printed {'fish', 'dog', 'cat'}.

Most often, you make a set from a list with set(). It's the quickest way to get rid of duplicates:

votes = ["zoo", "castle", "zoo", "aquapark", "zoo"]
places = set(votes)
print(len(votes), len(places))
print("castle" in places)
print("museum" in places)
5 3
True
False

Five votes, but only three different places. in works as it does with a list: it tells you whether a value is in the set.

Watch out for one trap: {} isn't an empty set, it's an empty dictionary. An empty set is written set(), and that's also how Python prints it.

Instructions

  1. 1

    Make a set users from the list visits, and print how many different users signed in: Users: 4. Keep the line with the list: the exercise also tries other visits.

  2. 2

    Below, check with in whether "lily" is among the users: print Lily was here. if she is, and Lily wasn't here. if she isn't.

Back

7/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.