Skip to content

Python Set Intersection: Guide with Examples

Python Set Intersection Guide with Examples Cover Image

In this post, you’ll learn how to find the intersection between two or more sets in Python. Sets in Python are a built-in data type, where items are unordered, unindexed, and unique. By finding the intersection between two or more sets, you’re finding the elements that are common between the sets.

By the end of this tutorial, you’ll have learned:

  • How to use the Python set.intersection() method to find intersections between sets, lists, and other iterables
  • How to use the & operator to find the intersection between two or more sets
  • How to streamline finding the set intersection using the * unpacking operator
  • How to handle errors when finding the intersection between iterables

Table of Contents

Understanding Set Intersection in Python

Set intersection refers to finding the set of items that are common between two or more different sets, lists, tuples or other containers. This means that a set is returned that includes only items that exist in both sets (or in all of the sets if more than two sets are evaluated).

Because Python sets contain only unique items, each item will be represented only once. This is true even when you try to find the intersection between a set and a list (as you’ll learn later in this tutorial) – even if the list has the same item repeated multiple times. Looking to work only with lists? Check out my in-depth guide on finding the intersection between two Python lists.

The intersection between two (or more) sets can be easily represented using a venn diagram, as shown below:

Understanding Set Intersection in Python
Understanding what is meant by set intersection

Now that you have an understanding of what is meant by intersection, let’s dive into understanding the set .intersection() method.

Understanding the Python Set intersection Method

Python sets have a method, .intersection(), available to them that allow you to easily identify the intersection between two sets (or a set and another container object). Let’s take a look at what this method looks like:

# Understanding the Python set.intersection() Method
set.intersection(set1, set2, ...)

While the definition above identifies passing in sets, the .intersection() method actually allows you to pass in other container data types, such as lists and tuples. One important thing to note is that the method will always return a set.

Let’s see how we can use the .intersection() method to find the intersection between two sets:

# Finding the Intersection Between Two Sets
A = {1, 2, 3}
B = {2, 3, 4}

AnB = A.intersection(B)
print(AnB)

# Returns: {2, 3}

In the following section, you’ll learn how to use the intersection method between a set and a list in Python.

How to Find the Intersection Between a Set and a List in Python

The Python set intersection method allows you to find the intersection between a set and a Python list. Because sets contain only unique items, the resulting set will contain each item only one time. This is true, even if it exists multiple times in a Python list.

Let’s see what happens when we use the .intersection() method to find the intersection between a Python set and a list.

# Finding the Intersection Between a Set and a List in Python
A = {1, 2, 3}
B = [2, 3, 4]

AnB = A.intersection(B)
print(AnB)

# Returns: {2, 3}

We can see that by using the .intersection() method on a set and passing in a list, that the common items between the two objects are returned in a set.

How to Find the Intersection Between Multiple Sets in Python Using *

The Python set .intersection() method allows you to find the intersection between multiple sets. This can be done by passing in any number of sets into the method. Let’s see how we can find the intersection between three sets:

# Finding the Intersection Between Multiple Sets in Python
A = {1, 2, 3}
B = {2, 3, 4}
C = {3, 4, 5}

AnB = A.intersection(B, C)
print(AnB)

# Returns: {3}

We can simplify this process as well if all the sets are contained in a single list. We can then use the * operator to unpack all the items in the list directly. Let’s see what this looks like:

# Finding the Intersection Between Multiple Sets in Python Using *
A = {1, 2, 3}
B = {2, 3, 4}
C = {3, 4, 5}

sets = [A, B, C]

AnBnC = A.intersection(*sets)
print(AnBnC)

# Returns: {3}

In the following section, you’ll learn how to use the & operator to find the intersection between two or more sets in Python.

Using & to Find the Intersection Between Python Sets

A very elegant way to find the intersection between two or more sets in Python is to use the & operator. This allows us to write very Pythonic code that can be quite easy to understand. Let’s see what this looks like when we find the intersection between two sets:

# Finding the Intersection Between Two Sets Using &
A = {1, 2, 3}
B = {2, 3, 4}

print(AnB)
AnB = A & B

# Returns: {2, 3}

We can see that this accomplishes the same thing as using the .intersection() method. We can also accomplish this with more than sets, simply by chaining the operator. Let’s take a look at what this looks like:

# Finding the Intersection Between Three Sets Using &
A = {1, 2, 3}
B = {2, 3, 4}
C = {3, 4, 5}

AnBnC = A & B & C

print(AnBnC)
# Returns: {3}

In the following section, you’ll learn some of the quirks of the & operator.

Handling TypeError When Finding Set Intersection in Python

While the Python set.intersection() method works with a set and a different container data type, the & operator does not. The operator only works between sets, regardless of the number of sets. Let’s see what happens when we use the operator between a list and a set:

# Raising a Type Error When Finding the Intersection Between a List and a Set
A = {1, 2, 3}
B = [2, 3, 4]

AnB = A & B

# Raises: TypeError: unsupported operand type(s) for &: 'set' and 'list'

We can resolve this error in two ways:

  1. We can convert the list to a set, by passing it into the set() function
  2. We can pass the list into the .intersection() method

Let’s see what both of these methods look like:

# Resolving the TypeError
A = {1, 2, 3}
B = [2, 3, 4]

# Method 1: Converting to a set
AnB = A & set(B)

# Method 2: Using .intersection()
AnB2 = A.intersection(B)

print(AnB)
print(AnB2)

# Returns:
# {2, 3}
# {2, 3}

In the following section, you’ll learn how to work with empty sets when attempting to find the intersection.

Working with Empty Sets When Finding Set Intersections

When you try to find the intersection between a set and an empty set, an empty set will always be returned. This happens, logically, because an empty set will have zero items in common with any other set.

Let’s see what this looks like:

# Finding the Intersection Between a Set and an Empty Set
A = {1, 2, 3}
B = set()

AnB = A.intersection(B)
print(AnB)

# Returns:
# set()

Frequently Asked Questions

What is the best way to find the intersection between two sets in Python?

The best way to find the intersection between two or more sets is to use the .intersection() method. This method allows you to even find the intersection between a set and other data types.

How do you find the intersection between two lists or tuples in Python?

To find the intersection between between lists and tuples in Python, you can convert one of them to a set and pass the other into the .intersection() method. This process can look like this: set(list1).intersection(list2).

Conclusion

In this tutorial, you learned how to use Python to find the intersection between two or more sets. You first learned what is meant by finding the intersection between two sets. Then, you learned how to use the .intersection() method to find the intersection between two or more sets or between sets and other data types. Then, you learned how to use the & operator to find intersections.

Additional Resources

To learn more about related topics, check out the tutorials below:

  • How to Remove Items from Python Sets
  • Python frozenset: Overview and Examples
  • How to Append to a Set in Python: Python Set Add() and Update()
  • Python Sets: Official Documentation

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials. View Author posts

Tags: Python Python Sets

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Python in 30 days cover image

Learn Python in 30 days. For free.

.

玻璃钢生产厂家安徽景观玻璃钢雕塑供应商河北开业商场美陈供应商深圳商场玻璃钢雕塑设计厂家玻璃钢红军雕塑厂家联系方式金昌景区玻璃钢雕塑价格毕节地区玻璃钢雕塑大型的玻璃钢人物雕塑进口玻璃钢音符雕塑吉林特色玻璃钢雕塑方法玻璃钢菩萨雕塑价格玻璃钢仿铜雕塑性价比公司香港玻璃钢雕塑制作厂家萍乡定制玻璃钢雕塑价位河南玻璃钢牛动物雕塑制作工厂鞍山玻璃钢马雕塑玻璃钢沙桌雕塑定制玻璃钢花盆检验报告玻璃钢雕塑报价标准商场动物美陈图片大全红色玻璃钢人物雕塑供销玻璃钢景观雕塑商场美陈选什么经营范围马鞍山玻璃钢雕塑设计济源不锈钢人物玻璃钢彩绘雕塑安徽仿铜玻璃钢雕塑哪家便宜四川玻璃钢花盆供应平凉公园玻璃钢雕塑广东酒店艺术玻璃钢雕塑艺术摆件杭州商场美陈公司运城玻璃钢花盆香港通过《维护国家安全条例》两大学生合买彩票中奖一人不认账让美丽中国“从细节出发”19岁小伙救下5人后溺亡 多方发声单亲妈妈陷入热恋 14岁儿子报警汪小菲曝离婚始末遭遇山火的松茸之乡雅江山火三名扑火人员牺牲系谣言何赛飞追着代拍打萧美琴窜访捷克 外交部回应卫健委通报少年有偿捐血浆16次猝死手机成瘾是影响睡眠质量重要因素高校汽车撞人致3死16伤 司机系学生315晚会后胖东来又人满为患了小米汽车超级工厂正式揭幕中国拥有亿元资产的家庭达13.3万户周杰伦一审败诉网易男孩8年未见母亲被告知被遗忘许家印被限制高消费饲养员用铁锨驱打大熊猫被辞退男子被猫抓伤后确诊“猫抓病”特朗普无法缴纳4.54亿美元罚金倪萍分享减重40斤方法联合利华开始重组张家界的山上“长”满了韩国人?张立群任西安交通大学校长杨倩无缘巴黎奥运“重生之我在北大当嫡校长”黑马情侣提车了专访95后高颜值猪保姆考生莫言也上北大硕士复试名单了网友洛杉矶偶遇贾玲专家建议不必谈骨泥色变沉迷短剧的人就像掉进了杀猪盘奥巴马现身唐宁街 黑色着装引猜测七年后宇文玥被薅头发捞上岸事业单位女子向同事水杯投不明物质凯特王妃现身!外出购物视频曝光河南驻马店通报西平中学跳楼事件王树国卸任西安交大校长 师生送别恒大被罚41.75亿到底怎么缴男子被流浪猫绊倒 投喂者赔24万房客欠租失踪 房东直发愁西双版纳热带植物园回应蜉蝣大爆发钱人豪晒法院裁定实锤抄袭外国人感慨凌晨的中国很安全胖东来员工每周单休无小长假白宫:哈马斯三号人物被杀测试车高速逃费 小米:已补缴老人退休金被冒领16年 金额超20万

玻璃钢生产厂家 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化