Sets: a bag of things, without duplicates
A set is a bag where every item appears once, and the answer to "is it in there?" is always yes or no.
A set is a bag of things. You can throw Mila, Tom and Ana into one bag and call it A. The bag does not care about order, and it does not care how many times you dropped Mila in: a set holds each thing once. If you ask "is Tom in the bag?", the only possible answers are true or false. There is no "kind of".
Three operations cover most of what you will ever need. The union (A ∪ B) is the bag you get when you tip both bags into one: everything from A, everything from B, each name once. The intersection (A ∩ B) is only what sits in both bags. The difference (A \ B) is what is in A but not in B. Union reads as "or", intersection reads as "and", difference reads as "not in".
A = { Mila, Tom, Ana }
B = { Tom, Ana, Ben }
A ∪ B (union, "or") = { Mila, Tom, Ana, Ben }
A ∩ B (intersection, "and") = { Tom, Ana }
A \ B (difference, "not in") = { Mila }
Tom ∈ A -> true
Ben ∈ A -> falseMembership is a yes/no question:
This matters because a set answers a question with a yes or a no, and computers are extremely good at yes-or-no questions. Every "have I seen this user before?" and every "does this word already exist?" is a membership test, and the whole point of picking a set over a list is that the set answers much faster.
Practice
Match each set expression with the result it produces for A = { Mila, Tom, Ana } and B = { Tom, Ana, Ben }.
Hints
- A ∪ B is everything that is in A, in B, or in both.
- A \ B throws out anything that also appears in B.
12 XP
The football group is Ana, Ben, Tom. The chess group is Ben, Tom, Lena. Who is in both groups?
Hints
- Ask who is in BOTH lists, not who is in either one.
- Ana is in the football list only, so she cannot be in the answer.
11 XP
Put the steps of "build a set from a list" in the order they must happen for the list [Tom, Ana, Tom, Ben].
Hints
- Add to the result only when the name is not already in it.
- Every name in the list gets looked at, even the ones already in the result.
12 XP