PYTHON
Manage Unique Elements and Perform Set Operations with Python Sets
Learn to use Python sets for efficiently storing unique elements, performing fast membership tests, and executing set operations like union, intersection, and difference.
# Removing duplicates from a list
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_elements = set(my_list)
print(f"Unique elements: {list(unique_elements)}")
# Fast membership testing
known_ids = {101, 105, 203, 405}
user_id = 105
if user_id in known_ids:
print(f"User {user_id} is a known ID.")
# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print(f"Union (A | B): {set_a | set_b}")
print(f"Intersection (A & B): {set_a & set_b}")
print(f"Difference (A - B): {set_a - set_b}")
How it works: Python sets are unordered collections of unique elements. They are highly efficient for tasks like removing duplicate items from a list, performing very fast membership tests (checking if an item exists in the set), and executing mathematical set operations such as union (combining elements from both sets), intersection (finding common elements), and difference (finding elements unique to one set). This makes them invaluable for data cleaning and comparison.