Add and lookup
- Algorithms course
- Beginner
- Lesson 74/80
- 4 min
Add to a set and check membership.
Intersection and union
The intersection of two sets is the elements in both. The union is all elements in at least one set.
Intersection: A & B or A.intersection(B). Union: A | B or A.union(B).
Difference and subset
Set difference: elements in A but not in B (A - B). Subset: if all of A's elements are in B, A is a subset of B.
These operations form the basis of set theory and are frequently used in data analysis.
Practice Set contains
Write set_contains(s, item). Return True if item in s, False otherwise. Print True with print(set_contains({1, 2, 3}, 2)).
Starter code
def set_contains(s, item):
# ContainsSample solution
def set_contains(s, item):
# Contains
return item in s
print(set_contains({1, 2, 3}, 2))Expected output
True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Intersection
The intersection of two sets is found with the ____ operator.
The intersection of two sets is found with the & operator.
Explanation: & is right.
2 Add and lookup: match the terms
| Term | Meaning |
|---|---|
intersection |
A & B |
union |
A | B |
difference |
A - B |
subset |
A ⊆ B |
3 What does A | B give?
- Difference Correct answer
- Union
- Intersection
- Subset
Explanation: A | B gives the union.