📚 A comprehensive guide to Python's set data structure
Sets in Python are unordered, unindexed, and unique collections of elements. They are ideal for tasks like eliminating duplicates or performing mathematical set operations.
Key Features of Sets
💡 Fast lookups: Checking if an element exists in a set is O(1) time complexity.
💡 Unique elements: Sets automatically remove duplicates.
💡 Mathematical operations: Support union, intersection, difference, and symmetric difference.
Common Operations
🔧 Creating a set:
my_set = {1, 2, 3}
# or my_set = set([1, 2, 3])
🔧 Adding elements:
my_set.add(4)
🔧 Removing elements:
my_set.remove(2) # or my_set.discard(2)
🔧 Set methods:
len(my_set)
→ Get the number of elementsmy_set.union()
→ Combine setsmy_set.intersection()
→ Find common elementsmy_set.isdisjoint()
→ Check for no overlap
Practical Examples
📝 Example 1: Removing duplicates
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}
📝 Example 2: Set operations
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print(set_a.union(set_b)) # Output: {1, 2, 3, 4, 5}
print(set_a.intersection(set_b)) # Output: {3}
Applications of Sets
🚀 Use Case 1: Data processing (e.g., filtering unique values)
🚀 Use Case 2: Membership testing (e.g., checking if a key exists in a dictionary)
🚀 Use Case 3: Eliminating duplicates in lists
For more advanced topics on Python sets, visit our Sets Operations Guide 📚