Python Set Intersection – The Ultimate Guide for Beginners
In the last week's article, you've learned what Python set
Today you'll learn everything there is about Python set intersection. You'll be ready to use it with confidence after reading the article.JNNC Technologies Pvt.Ltd
Python Set Intersection – The Basics
So, what is Python set intersection? That's what we'll answer in this section. You'll get a complete understanding of the definition, syntax, and return values through visual examples.
Definition and usage
Set intersection function returns the common element(s) of two or more sets. For example, I like to code in Python, JavaScript, and PHP, and you use Java, Python, and Ruby. We both have Python in common. We'll work with two sets throughout the article just to keep things simple, but the same logic applies when intersecting more of them.
Only Python is common to both sets, so I've highlighted the intersection area in blue.
What does intersection method do in Python and how do you find the intersection between sets? Let's go over the syntax to answer these questions.
Syntax
Where:
- set1– The iterable to find intersection from.
- set2,set3– Other sets use to calculate intersection.
Return value
The intersection function returns a new set which is the intersection between the first set and all other sets passed as arguments – but only if set(s) or iterable object(s) were passed to the function.
If no arguments were passed into the
Python Set Intersection Function Example
We'll declare two sets, just as on Image 1:
- A: Contains Python, JavaScript, and PHP
- B: Contains Java, Python, and Ruby
Only Python is present in both sets, so calculating an intersection should return a new set with Python being the only element:
Output:
If you don't specify any parameters to the intersection function, a copy of the set is returned:
Output:
You can verify it was copied by printing the memory address:
0 Comments
If you have any doubts,please let me know