Code Explanation:
1. Creating Sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set1: Contains the elements {1, 2, 3, 4, 5}.
set2: Contains the elements {4, 5, 6, 7, 8}.
Sets in Python:
Unordered collections of unique elements.
Duplicate elements are not allowed.
Supports set operations like union, intersection, difference, etc.
2. Using difference()
result = set1.difference(set2)
The difference() method finds elements that are in set1 but not in set2.
It compares set1 and set2 element by element:
In set1 but not in set2: {1, 2, 3}.
Shared elements: {4, 5} (ignored in the result).
Only in set2: {6, 7, 8} (irrelevant for this operation).
Result:
result = {1, 2, 3} (a new set containing only the unique elements from set1 that are not in set2).
3. Output (if printed)
If you add:
print(result)
The output would be:
{1, 2, 3}
0 Comments:
Post a Comment