Python: Create set difference
8. Create Set Difference
Write a Python program to create set difference.
Visual Presentation:
Sample Solution-1:
Using difference() Method
Python Code:
Sample Output:
Original sets: {'green', 'blue'} {'yellow', 'blue'} Difference of setc1 - setc2: {'green'} Difference of setc2 - setc1: {'yellow'} Original sets: {1, 2, 3, 4, 5} {1, 5, 6, 7, 8, 9} Difference of setn1 - setn2: {2, 3, 4} Difference of setn2 - setn1: {8, 9, 6, 7}
Sample Solution-2:
Using - Operator
Python Code:
Sample Output:
Original sets: {'blue', 'green'} {'yellow', 'blue'} Difference of setc1 - setc2: {'green'} Difference of setc2 - setc1: {'yellow'} Original sets: {1, 2, 3, 4, 5} {1, 5, 6, 7, 8, 9} Difference of setn1 - setn2: {2, 3, 4} Difference of setn2 - setn1: {8, 9, 6, 7}
Sample Solution-3:
Multiple sets in the difference() method
Python Code:
Sample Output:
Original sets: {1, 2, 3, 4, 5} {1, 5, 6, 7, 8, 9} {3, 4, 5, 9, 10} {5, 7, 9, 10, 12, 14} Difference of setn1 - setn2,setn3,setn4: {2} Difference of setn4 - setn1,setn2,setn3: {12, 14}
For more Practice: Solve these Related Problems:
- Write a Python program to compute the difference between two sets using the - operator.
- Write a Python program to use the difference() method to remove elements of one set from another.
- Write a Python program to implement a function that returns elements in set A that are not in set B.
- Write a Python program to compare two sets and print the elements that are unique to each using set difference.
Go to:
Previous: Write a Python program to create a union of sets.
Next: Write a Python program to create a symmetric difference.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.