← Back to all snippets
PYTHON

Managing Unique Elements and Set Operations

Master Python's `set` data structure for removing duplicates, performing unions, intersections, and differences efficiently on collections of items.

# Remove duplicates from a list
numbers = [1, 2, 2, 3, 4, 4, 5, 1]
unique_numbers = set(numbers)
print(f"Original list: {numbers}")
print(f"Unique numbers (set): {unique_numbers}")
print(f"Unique numbers (list): {list(unique_numbers)}")

# Set operations
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}

print(f"Set A: {set_a}")
print(f"Set B: {set_b}")

# Union (elements in A or B or both)
union_set = set_a.union(set_b)
print(f"Union (A | B): {union_set}")

# Intersection (elements in both A and B)
intersection_set = set_a.intersection(set_b)
print(f"Intersection (A & B): {intersection_set}")

# Difference (elements in A but not in B)
difference_set = set_a.difference(set_b)
print(f"Difference (A - B): {difference_set}")

# Symmetric Difference (elements in A or B but not both)
symmetric_difference_set = set_a.symmetric_difference(set_b)
print(f"Symmetric Difference (A ^ B): {symmetric_difference_set}")
How it works: Python's `set` is an unordered collection of unique hashable elements. It's highly optimized for checking membership and performing mathematical set operations like union, intersection, difference, and symmetric difference. Converting a list to a set is a common and efficient way to remove duplicate items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs