PythonDictionaries and sets
set. intersection()
Returns a new set with the elements that appear in every given set.
- Returns
- A new set.
- Changes the original
- No
Example
#Python
html_students = {"Emma", "Jack", "Mia", "Ivy"}
python_students = {"Jack", "Ivy", "Noah"}
both = html_students.intersection(python_students)
print(sorted(both))
print(sorted(html_students & python_students))Resultsaved result, you can check it
['Ivy', 'Jack']
['Ivy', 'Jack']
Definition and usage
#The intersection() method finds the common part of sets: only the elements present in all of them at once make it into the result. The original sets stay unchanged.
The shorter way to write it is the & operator: a & b. As with the union, the method accepts several arguments and any collection, while the operator only works on sets.
Typical uses are the shared interests of two users, tags that match a filter, or students enrolled in several courses. If you only want to know whether two sets have nothing in common, use the isdisjoint() method. It then returns True and builds no new set.
Syntax
#Syntax
set.intersection(*others)
set & otherParameters
#*others
sets or other collections
The collections you are looking for shared elements with.
More examples
#Python
monday = {"Emma", "Jack", "Mia"}
tuesday = {"Jack", "Mia", "Ivy"}
wednesday = ["Mia", "Jack", "Noah"]
print(sorted(monday.intersection(tuesday, wednesday)))
print(monday.isdisjoint({"Noah", "Ivy"}))
print(monday.isdisjoint({"Emma"}))Resultsaved result, you can check it
['Jack', 'Mia']
True
False
Python
lesson_tags = {"python", "loops", "lists"}
filters = {"lists", "dicts"}
common = lesson_tags & filters
if common:
print("Matches the filter:", sorted(common))Resultsaved result, you can check it
Matches the filter: ['lists']
Good practices
#- An empty set counts as false, so
if a & b:checks whether two sets share any elements. - The
intersection_update()method and the&=operator keep only the shared elements in the set, changing it in place.
Related entries
#- set.union()Returns a new set with the elements from every given set, without duplicates.
- set.difference()Returns a new set with the elements of the first set that are not in the others.
- dict.keys()Returns a view of the dictionary's keys that always reflects its current contents.
- set()Creates a set: an unordered collection of unique items.
Spotted a mistake or missing an example? Write to us.