liveBook · Manning

Set intersection

As explained in Python How-To

Set intersection is the operation that produces the elements common to two sets or set-compatible collections.

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.
CH03_F08_Cui

A visual comparison places intersection alongside union, symmetric difference, and difference, clarifying how each operation selects members. section 3.6.3

How Python How-To covers it

How deep it goes
Explains operators, methods, Boolean conversion, iterable inputs, and unordered results, but does not develop implementation internals.
Examples
Demonstrates shared stock symbols, list operands, the & operator, intersection(), and bool().
What it assumes
Assumes familiarity with Python lists, sets, iterables, and Boolean values while demonstrating the operation through concrete collections.
What you can do after
Apply it via Python sets to retrieve common elements or test whether collections overlap.
How it connects
Connects intersection with sets, membership testing, union, symmetric difference, difference, iterables, and Boolean evaluation.

Also explained in

Compare how 5 books explain set intersection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.