PYTHON

Perform Efficient Set Operations and Uniqueness

Explore Python's `set` data structure to quickly find unique elements, perform unions, intersections, and differences, optimizing data manipulation tasks.

# Create sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
list_with_duplicates = [1, 2, 2, 3, 4, 4, 5, 1]

print(f"Set 1: {set1}")
print(f"Set 2: {set2}")

# 1. Remove duplicates from a list
unique_elements = list(set(list_with_duplicates))
print(f"Unique elements from list: {unique_elements}")

# 2. Union: Elements in either set1 OR set2
union_set = set1.union(set2)
# union_set = set1 | set2 # Alternative operator syntax
print(f"Union (set1 | set2): {union_set}")

# 3. Intersection: Elements in BOTH set1 AND set2
intersection_set = set1.intersection(set2)
# intersection_set = set1 & set2 # Alternative operator syntax
print(f"Intersection (set1 & set2): {intersection_set}")

# 4. Difference: Elements in set1 BUT NOT in set2
difference_set1 = set1.difference(set2)
# difference_set1 = set1 - set2 # Alternative operator syntax
print(f"Difference (set1 - set2): {difference_set1}")

# 5. Symmetric Difference: Elements in either set1 or set2, BUT NOT in both
symmetric_difference_set = set1.symmetric_difference(set2)
# symmetric_difference_set = set1 ^ set2 # Alternative operator syntax
print(f"Symmetric Difference (set1 ^ set2): {symmetric_difference_set}")

# 6. Check subset/superset
subset_check = {1, 2}.issubset(set1)
superset_check = set1.issuperset({1, 6})
print(f"Is {{1, 2}} a subset of set1? {subset_check}")
print(f"Is set1 a superset of {{1, 6}}? {superset_check}")
How it works: Python's `set` data structure is an unordered collection of unique hashable elements. It's highly efficient for tasks like removing duplicates from a list and performing mathematical set operations such as union, intersection, difference, and symmetric difference. This snippet demonstrates these core functionalities, which are invaluable for data cleaning, comparison, and analysis.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs