Python Set intersection() Method

A.intersection(B) returns a new set containing elements common to both inputs. The & operator is the set-to-set equivalent. The original sets are not changed.

The method form can accept iterable arguments; operator forms require set-like operands. Use intersection_update() when the original set should be reduced in place. See the Set operations overview.

Set order: sets are unordered. Whenever an example prints a set, the displayed element order can differ between runs or Python environments.

  • Video Tutorial on Set


intersection using & operator

set operation intersection All distinct elements from both sets
Using ampersand ( & ) operator
A={1,2,3}
B={3,4,5}
print(A & B)
Output ( Note 3 is the only common element )
{3}

Using type()

We can check the output by using type()
A={1,2,3}
B={3,4,5}
x=A & B 
print(type(x))
Output
<class 'set'>

Using intersection() method

A={'a','b','c'}
B={'a','y','z'}
print(A.intersection(B))
Output
{'a'}

Using More Than Two Sets

We can use any number of sets with intersection()
A={'a','b','c'}
B={'a','y','z'}
C={'a','k','l'}
print(A & B & C)
Output
{'a'}

intersection() method

Using string ( iterable object ) with intersection() method
A={'a','b','c','x','y'}
B='Alex'
print(A.intersection(B))
Output
{'x'}
Using list with intersection() method.
A={'a','b','c'}
B=['a','x','y']
print(A.intersection(B))
Output
{'a'}
Below code will generate error.
print(A & B)
 TypeError: unsupported operand type(s) for &: 'set' and 'list'

intersection_update()

In all above code by using intersection() we created a new set. By using intersection_update() method we can change the original set with common elements.
All Set Methods Set Operations Questions with solutions on set
union() difference() symmetric_difference()


Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer