Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

Python Set Intersection: Methods and Operators

  • Safa MulaniSafa Mulani
  • November 28, 2026
  • Python Set
Python Set Intersection: Methods and Operators

To find values shared by Python sets, use set intersection. A set intersection is a new set containing values found in every input.

I’ll show you how to use intersection() to find shared values and how to change the first set instead of making a separate result.

TL;DR

Use intersection() for a new set and for iterable arguments, or use & when both inputs are sets.

  • Use left.intersection(right) to keep the inputs unchanged.
  • Use left.intersection_update(right) to change the left set in place.
  • Both forms can compare several inputs and return only values present in all of them.

What Is Python Set Intersection?

A set intersection is a new set containing values found in every input. Python sets store distinct hashable values, so mutable values such as lists cannot be members.

The operation compares membership rather than positions, so each shared value appears once. I prefer intersection() here because its name makes the operation clear and accepts the list shown in the demo.

The method call has the form first.intersection(other, …). The first set is the receiver, and each later argument supplies another collection to compare. A string is iterable too, but its characters become the candidate values, which may not match the intended data model.

This makes the method useful for checking shared tags, permissions, or identifiers gathered from different sources. The meaning of equality still depends on the values: a string matches the same string, and an integer matches the same integer. Intersection does not normalize case or convert values such as “4” into 4.

For sets such as {1, 2, 3} and {2, 3, 4}, the intersection is {2, 3}. The intersection() method accepts iterable arguments such as lists, while the & operator expects set operands.

  • Python set type
  • Bitwise operators

How to Find a Set Intersection Step by Step

Start with the values to compare, then choose the method or operator based on your input types and whether the original set must remain intact.

Step 1: Intersect two sets with intersection()

Call the method on the first set and pass the second set as an argument.

left = {1, 2, 3, 4}
right = {3, 4, 5}
extra = [4, 6]

print(left.intersection(right, extra))
print(left & right)
print(left)

Run python3 set_intersection_demo.py. It prints:

{4}
{3, 4}
{1, 2, 3, 4}
Terminal output comparing intersection() and the ampersand operator
The method accepts a list argument, while the original set stays unchanged.

The first line includes 4 because it appears in all three inputs. The second line shows the two-set operator result. The final line prints left so you can compare it with the values listed at the start.

Step 2: Compare three or more collections

When an application stores sets in a list, call set.intersection(*groups) to pass them in one operation. Check that the list is nonempty because the first set supplies the receiver.

Step 3: Update the first set in place

intersection_update() returns None. Its operator counterpart, &=, also changes the left set when both operands are sets.

A second name pointing to that same object sees the updated members too. Copy the set first when the two names need independent contents.

Set Intersection Edge Cases

A failed operator expression identifies the incompatible operand types in its exception.

CaseWhat happensWhat to do
No shared valuesThe result is set().Check for an empty result before using it.
List passed to &Python raises a TypeError.Use intersection() or convert the list with set(values).
Empty set literal{} creates a dictionary.Use set() to create an empty set.

I tested the incompatible operands and got TypeError: unsupported operand type(s) for &: ‘set’ and ‘list’. Use intersection() for that list input or convert its elements to a set first.

Repeated source values collapse during set construction. For example, set([2, 2, 3]) contains only 2 and 3, so use collections.Counter when occurrence counts matter.

Use isdisjoint() for a yes-or-no overlap check. It returns True when no values are shared.

A result may print in a different order because sets do not promise a display order. Sort the result before formatting it when a report or test needs stable text.

Conclusion

The Python set reference lists the supported operations and their method signatures. Review it when choosing an operation for a larger data-processing task.

FAQ

These answers cover common choices when comparing Python sets.

How do I find the intersection of three sets in Python?

Call first.intersection(second, third), or use first & second & third when all operands are sets. The result contains values present in every set.

Does intersection() change the original set?

No. intersection() returns a new set. Use intersection_update() or &= to change the existing set.

Why does set intersection remove duplicate values?

A set stores distinct values rather than occurrence counts, so an intersection contains each shared value once.

Safa Mulani
Safa Mulani

An enthusiast in every forthcoming wonders!

Articles: 189
Python Reverse List: Methods and Examples
Previous Post Python Reverse List: Methods and Examples
Next Post How to Use Input Function in Python
How to Use Input Function in Python

Related Posts

Python Nested Sets: Create a Set of Groups

Python Nested Sets: Create a Set of Groups

  • November 12, 2026
Python Sets: Fix the Indexing TypeError

Python Sets: Fix the Indexing TypeError

  • November 4, 2026
Jaccard Similarity and Jaccard Index using Python and NLP

Jaccard Similarity and Jaccard Index using Python and NLP

  • September 13, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.