We have already seen the Functions to add a Set to an existing Set. Now, let us look at the Functions to Join two Sets and initialise it to a third Set.
Let us take the same example, where we have a Set that contains three names, 'Mohan', 'Kriti' and 'Salim'.
And we have a second 'Set' that contains three names 'Sia', 'Andrew' and 'Kriti'.
And we need to create a new Set that will have the values from both the Sets.
There are three Functions that will help us achieve the same :
Let us see the 'union( )' Function first.
x = {"Mohan", "Kriti", "Salim"} y = {"Sia", "Andrew", "Kriti"} z = x.union(y) print(z)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Then what we have done is, put the names, 'Sia', 'Andrew' and 'Kriti' in another set 'y'.
And used the 'union( )' Function to join the Set 'x'(With values 'Kriti', 'Mohan' and 'Salim') with the Set 'y'(With values 'Sia', 'Andrew' and 'Kriti').
And assign it to a new variable 'z'.
And since, 'Kriti' is present in both the Sets, 'Kriti' will be added once. Else it might cause a dupicate entry.
And we get the below output,
So, as said, 'update( )' Function keeps the values from both sides.
Let us see the 'intersection( )' Function next. As the name suggests, the 'intersection( )' Function takes the values from both the sets and only value that is common in both Sets are taken and initialised to the third Set.
Since, 'Kriti' is the common value in both the Sets, 'intersection()' Function would just take the name 'Kriti'.
x = {"Mohan", "Kriti", "Salim"} y = {"Sia", "Andrew", "Kriti"} z = x.intersection(y) print(z)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Then what we have done is, put the names, 'Sia', 'Andrew' and 'Kriti' in another set 'y'.
And used the 'intersection( )' Function next to take the common value and initialise to the third variable 'z'.
And since, 'Kriti' is present in both the Sets, only 'Kriti' will be present in the new Set 'z'.
And we get the below output,
Next, let us see the 'symmetric_difference( )' Function. As the name suggests, the 'symmetric_difference( )' Function takes those values that are not present in both the sets.
Since, 'Kriti' is the common value in both the Sets, 'symmetric_difference( )' Function would exclude the name 'Kriti'.
x = {"Mohan", "Kriti", "Salim"} y = {"Sia", "Andrew", "Kriti"} z = x.symmetric_difference(y) print(x)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Then what we have done is, put the names, 'Sia', 'Andrew' and 'Kriti' in another set 'y'.
And used the 'symmetric_difference( )' Function next.
And since, 'Kriti' is present in both the Sets, only 'Kriti' would be excluded in the new Set 'z'.
Rest of the values would be taken.
And we get the below output,