Home / Programs / Find the intersection (common) of two sets and remove those elements from the first set
🚀 Programming Example

Find the intersection (common) of two sets and remove those elements from the first set

👁 485 Views
💻 Practical Program
📘 Step Learning
Find the intersection (common) of two sets and remove those elements from the first set

📌 Information & Algorithm

Given Input:

first_set = {23, 42, 65, 57, 78, 83, 29}
second_set = {57, 83, 29, 67, 73, 43, 48}

Expected Output:

Intersection is  {57, 83, 29}
First Set after removing common element  {65, 42, 78, 23}

Use the intersection() and remove() method of a set

💻 Program Code

first_set = {23, 42, 65, 57, 78, 83, 29}
second_set = {57, 83, 29, 67, 73, 43, 48}

print("First Set ", first_set)
print("Second Set ", second_set)

intersection = first_set.intersection(second_set)
print("Intersection is ", intersection)
for item in intersection:
    first_set.remove(item)

print("First Set after removing common element ", first_set)
                        

🖥 Program Output

First Set  {65, 42, 78, 83, 23, 57, 29}
Second Set  {67, 73, 43, 48, 83, 57, 29}
Intersection is  {57, 83, 29}
First Set after removing common element  {65, 42, 78, 23}
                            

📘 Explanation

  • Get the common items using the first_set.intersection(second_set)
  • Next, iterate common items using a for loop
  • In each iteration, use the remove() method of on first set and pass the current item to it.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.