Click for All Topics
&
operator in place of .intersection()
method.Syntax –
set_name.intersection(iterable1,iterable2,iterable3,...)
Parameters –
Example –
set1={1,2,3,4,5}
set2={3,4,5,6,7}
print("Set 1:",set1)
print("Set 2:",set2)
s=set1.intersection(set2)
print("Resultant set:",s)
# Output -
# Set 1: {1, 2, 3, 4, 5}
# Set 2: {3, 4, 5, 6, 7}
# Resultant set: {3, 4, 5}
Intersection method with no argument –
Example –
s={'Hello','Everyone','this','is','edSlash'}
print("Set 1:",s)
s1=s.intersection(s1)
print("Resultant set:",s1)
# Output -
# Set 1: {'Hello','Everyone','this','is','edSlash'}
# Resultant set: {'Hello','Everyone','this','is','edSlash'}
Intersection with two arguments or intersection of three sets –
Example –
s={11,12,13,14,15}
s1={12,14,16,11}
s2={11,13,14}
print(s)
print(s1)
print(s2)
resultant_set=s.intersection(s1,s2)
print("resultant set:",resultant_set)
# Output -
# {11, 12, 13, 14, 15}
# {16, 11, 12, 14}
# {11, 13, 14}
# resultant set: {11, 14}
Intersection with no common elements –
Example –
my_set1={10,20,30,40,50}
my_set2={'A','B','C','D','E'}
print("Set 1:",my_set1)
print("Set 2:",my_set2)
s=my_set1.intersection(my_set2)
print("Resultant set:",s)
# Output -
# Set 1: {50, 20, 40, 10, 30}
# Set 2: {'A', 'C', 'D', 'E', 'B'}
# Resultant set: set()
Intersection with another type of iterable or collection element e.g. list, tuple, dictionary, string-
Example –
my_set={'a','b','c','f','g','h'}
my_list=['a','b','c','d','e']
my_tuple=('a','b','c')
my_dict={'a':12,'b':15}
my_string='ab'
returned_set=my_set.intersection(my_list,my_tuple,my_dict,my_string)
print('set:',my_set)
print('list:',my_list)
print('tuple:',my_tuple)
print('dictionary:',my_dict)
print('string:',my_string)
print('Resultant set:',returned_set)
# Output -
# set: {'c', 'h', 'f', 'a', 'b', 'g'}
# list: ['a', 'b', 'c', 'd', 'e']
# tuple: ('a', 'b', 'c')
# dictionary: {'a': 12, 'b': 15}
# string: ab
# Resultant set: {'a', 'b'}
Intersection using & operator –
Example –
Science_stream_subject={'Hindi','English','Math','Physics','Chemistry'}
Commerce_stream_subject={'Hindi','English','Accountancy','Business Studies','Economics'}
print("Science stream subject:",Science_stream_subject)
print("Commerce stream subject:",Commerce_stream_subject)
common_subject=Commerce_stream_subject & Science_stream_subject
print("Common subject:",common_subject)
# Output -
# Science stream subject: {'Hindi', 'English', 'Chemistry', 'Math', 'Physics'}
# Commerce stream subject: {'Business Studies', 'Economics', 'English', 'Accountancy', 'Hindi'}
# Common subject: {'Hindi', 'English'}
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India