w3resource

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

Python sets: Exercise-21 with Solution

Write a Python program to remove the intersection of a 2nd set from the 1st set.

Sample Solution:-

Python Code:

sn1 = {1,2,3,4,5}
sn2 = {4,5,6,7,8}
print("Original sets:")
print(sn1)
print(sn2)
print("Remove the intersection of a 2nd set from the 1st set using difference_update():")
sn1.difference_update(sn2)
print(sn1)
sn1 = {1,2,3,4,5}
sn2 = {4,5,6,7,8}
print("Remove the intersection of a 2nd set from the 1st set using -= operator:")
print(sn1-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 difference_update():
{1, 2, 3}
Remove the intersection of a 2nd set from the 1st set using -= operator:
{1, 2, 3}

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to check a given set has no elements in common with other given set.
Next: Python Collections Exercise Home.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Returns all the elements of a list except the last one

Example:

def tips_initial(lst):
  return lst[0:-1]

print(tips_initial([1, 2, 3, 4]))

Output:

[1, 2, 3]