Start learning free

LESSON 230 OF 673 · SETS

Sets in Python

Lesson

TL ; DR:

A set holds values without repeats. Adding a value that is already in it changes nothing.


colors = set()             # an empty set
colors.add("red")
colors.add("blue")
colors.add("red")          # already in it, no change

print(len(colors))         # 2
print("blue" in colors)    # True

pets = set(["cat", "dog", "cat"])
print(len(pets))           # 2


Full lesson:

A list keeps every value you put in it, repeats too. Sometimes you only need to know which values there are. A set is made for that.

A set holds each value once. Adding a value that is already in it changes nothing.

  • set() makes an empty set.
  • s.add(x) puts x in the set s.
  • x in s is True when x is in the set.
  • len(s) gives how many values the set holds.
  • set(lst) builds a set from the list lst. Its repeats go in once.

Checking x in s is fast, even for a big set. On a list, in looks at the values one by one.

A set has no order and no indexes. s[0] is an error. A printed set may show its values in any order.

Watch out for {}. It makes an empty dictionary, not an empty set. Write set() instead.


Your task

The camp's sign-up list, names, has some names twice. Build a set named kids from it.

Then Zoe signs up, and Ava signs up again. Add both names to kids.

Last, if "Leo" is in kids, print Leo is coming.

The code already prints the number of kids twice.

Expected output:

3 kids
4 kids
Leo is coming
STEP 1 OF 3
    Ctrl + Enter to check