w3resource

Python: Remove the intersection of a 2nd set from the 1st set

Python sets: Exercise-20 with Solution

Write a Python program to remove the intersection of a second set with a first set.

Visual Presentation:

Python Sets: Remove the intersection of a 2nd set from the 1st set.

Sample Solution:

Python Code:

# Create sets 'sn1' and 'sn2' with different elements.
sn1 = {1, 2, 3, 4, 5}
sn2 = {4, 5, 6, 7, 8}

# Print a message to indicate the original sets.
print("Original sets:")
print(sn1)
print(sn2)

# Print a message to indicate the removal of the intersection of the 2nd set from the 1st set using 'remove()'.
print("\nRemove the intersection of a 2nd set from the 1st set using remove():")

# Iterate over the elements in the intersection of 'sn1' and 'sn2' and remove them from 'sn1' using the 'remove()' method.
for i in sn1 & sn2:
    sn1.remove(i)

# Print the modified 'sn1' and the original 'sn2'.
print("sn1: ", sn1)
print("sn2: ", sn2) 

Sample Output:

Original sets:
{1, 2, 3, 4, 5}
{4, 5, 6, 7, 8}

Remove the intersection of a 2nd set from the 1st set using remove():
sn1:  {1, 2, 3}
sn2:  {4, 5, 6, 7, 8}

Python Code Editor:

Previous: Find the elements in a given set that are not in another set.
Next: Unique words and frequency from a given list of strings.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/sets/python-sets-exercise-21.php