A set is an unordered collection of elements. Each element can exist at most once in a set. There are no duplicate elements.
set_a = {1, 2, 3} set_b = {2, 3, 4} # Goal Intersect: {2, 3}
Goal: How to intersect to Python sets?
Solution: set_a & set_b
The set intersection operator set_a & set_b
intersects two sets, i.e., creates a new set with elements that exist in both sets set_a
and set_b
.
set_a = {1, 2, 3} set_b = {2, 3, 4} print(set_a & set_b) # Set Intersection: {2, 3}
A less concise alternative is the set method set_a.intersection(set_b)
that also creates a new set by intersecting both sets.
Set Intersection Puzzle Python
Here’s a puzzle regarding set intersection that’ll improve your Python skills:
# cancer-fighting foods cf = {"basil", "berries", "broccoli", "curcume", "garlic", "kale", "oranges", "seeds", "spinach", "sprouts"} # blood pressure reducing foods bf = {"bananas", "berries", "fish", "garlic", "kale", "red beets", "salmon", "seeds", "spinach", "yogurt"} # How many foods fight cancer & reduce blood pressure? print(len(cf & bf))
Puzzle: What is the output of this puzzle?
You can solve it on our interactive Python app here:
This puzzle is about two pieces of basic knowledge.
- The first piece of basic knowledge is what your mother always told you is true: vegetables and fruits are healthy. Eat 5 portions of vegetables and fruits per day or more and you will live longer.
- The second piece of basic knowledge is as profane as how to create and manipulate sets in Python. You need sets for all sorts of algorithms and code snippets to maintain data.
The one big advantage of sets over lists is that checking whether an element is in the set (containment operation) is much faster. No matter how large the set is, containment requires only constant time. In contrast, the containment operation for lists requires checking each list element. This becomes very slow for large lists.
In this puzzle, we want to know how many foods are both cancer-fighting and blood pressure reducing. This can be done with set intersection. Intersecting two sets A and B creates a new set with all elements that are contained in both sets A and B.
We can either use the intersection()
function or the '&'
operator to intersect two Python sets. In the puzzle are five foods that fight caner and reduce blood pressure: berries, garlic, spinach, kale, and seeds.
Studying Python sets in detail will make you a better coder. Period. Read this tutorial on Python sets to learn more!