PYTHON
Efficiently Manage Unique Elements with Sets
Learn how to use Python sets to store unique elements, perform fast membership tests, and apply set operations like union, intersection, and difference for data manipulation.
# Example 1: Creating a set and adding elements
tags = {"python", "webdev", "backend"}
print(f"Initial tags: {tags}") # Output: {'webdev', 'backend', 'python'} (order not guaranteed)
# Adding a new element
tags.add("flask")
print(f"Tags after adding 'flask': {tags}")
# Trying to add a duplicate element (no change)
tags.add("python")
print(f"Tags after adding 'python' again: {tags}")
# Example 2: Efficient membership testing (O(1) on average)
if "webdev" in tags:
print("'webdev' is in tags.")
if "frontend" not in tags:
print("'frontend' is not in tags.")
# Example 3: Set operations
user_interests = {"python", "devops", "cloud"}
all_skills = tags.union(user_interests) # or tags | user_interests
print(f"All unique skills (union): {all_skills}")
common_skills = tags.intersection(user_interests) # or tags & user_interests
print(f"Common skills (intersection): {common_skills}")
unique_to_tags = tags.difference(user_interests) # or tags - user_interests
print(f"Skills unique to 'tags': {unique_to_tags}")
# Example 4: Removing duplicates from a list
data_list = [1, 2, 2, 3, 1, 4, 5, 5]
unique_data = list(set(data_list))
print(f"Unique data from list: {unique_data}")
How it works: Python sets are unordered collections of unique elements. They are highly efficient for checking if an item is present (`in` operator) and for mathematical set operations like union, intersection, and difference. This makes them ideal for tasks such as filtering duplicate items from lists, managing unique tags or permissions, and performing fast lookups, which are common in web development contexts.