Set intersection selects the elements common to two sets. It is useful when a programming task asks whether collections overlap or which items satisfy both criteria. section 3.6.2 section 3.6.3
Find shared items
good_stocks = {"AAPL", "GOOG", "AMZN", "NVDA"} client = ["AMZN", "SNAP"] shared = good_stocks.intersection(client) print(shared) # {'AMZN'} print(bool(shared)) # True The & operator produces the same result for set operands: good_stocks & set(client). The method form accepts an iterable directly and is often clearer. section 3.6.2
Choose the form that matches the inputs and the result you need:
- Use & when both operands are sets and concise syntax improves readability. section 3.6.3
- Use intersection() when an operand is another iterable, such as a list, because conversion to a set is unnecessary. section 3.6.2 section 3.6.3
- Wrap the result in bool() when you need only whether at least one shared element exists. section 3.6.2
- Expect an unordered set result; do not rely on the displayed item order. section 3.6.3
Figure 3.8 Set operations in Python. Four common set operations are shown with their respective mathematical notations, Venn diagrams, and operations in Python. Union consists of members from A and B. Intersection consists of members common to A and B. Symmetric difference consists of members of one set but not both. Difference consists of members of one set but not both.
A visual comparison places intersection alongside union, symmetric difference, and difference, clarifying how each operation selects members. section 3.6.3




