PYTHON
Perform Set Operations for Unique Elements and Comparisons
Master Python's set data structure for efficient membership testing, removing duplicates, and performing powerful mathematical set operations like union and intersection.
def handle_unique_elements_and_operations(list1, list2):
"""
Demonstrates using Python sets for finding unique elements,
union, intersection, and difference between two lists.
"""
if not isinstance(list1, list) or not isinstance(list2, list):
raise TypeError("Inputs must be lists.")
# Convert lists to sets to automatically handle uniqueness and enable set operations
set1 = set(list1)
set2 = set(list2)
# 1. Get unique elements from a single list
unique_elements_list1 = set1
# 2. Union: Elements in either set
union_set = set1.union(set2) # or set1 | set2
# 3. Intersection: Elements common to both sets
intersection_set = set1.intersection(set2) # or set1 & set2
# 4. Difference (elements in set1 but not in set2)
difference_set1_2 = set1.difference(set2) # or set1 - set2
# 5. Symmetric Difference (elements in either set, but not in both)
symmetric_difference_set = set1.symmetric_difference(set2) # or set1 ^ set2
# 6. Check for subset/superset
is_subset = set1.issubset(set2)
is_superset = set1.issuperset(set2)
return {
"unique_list1": list(unique_elements_list1), # Convert back to list if needed
"union": list(union_set),
"intersection": list(intersection_set),
"difference_list1_minus_list2": list(difference_set1_2),
"symmetric_difference": list(symmetric_difference_set),
"list1_is_subset_of_list2": is_subset,
"list1_is_superset_of_list2": is_superset
}
# Example usage:
data1 = [1, 2, 3, 4, 5, 5, 4]
data2 = [4, 5, 6, 7, 8]
results = handle_unique_elements_and_operations(data1, data2)
# print(f"Set Operations Results: {results}")
# Expected:
# unique_list1: [1, 2, 3, 4, 5] (order might vary)
# union: [1, 2, 3, 4, 5, 6, 7, 8] (order might vary)
# intersection: [4, 5] (order might vary)
# difference_list1_minus_list2: [1, 2, 3] (order might vary)
# symmetric_difference: [1, 2, 3, 6, 7, 8] (order might vary)
# list1_is_subset_of_list2: False
# list1_is_superset_of_list2: False
How it works: This snippet demonstrates the power of Python's `set` data structure for efficient handling of unique elements and mathematical set operations. Sets automatically discard duplicate values upon creation. The example shows how to use sets to: (1) easily extract unique elements from a list, (2) find the `union` (all elements from both), `intersection` (common elements), `difference` (elements in one but not the other), and `symmetric_difference` (elements in either but not both) between two collections, and (3) check for `subset` and `superset` relationships. These operations are highly optimized (often O(N) or O(M) depending on the operation) and are crucial for tasks involving data de-duplication, comparison, and relationship testing.