๐ฎ Python Sets โ The Underrated Power of Set Operations
Python sets are unordered collections of unique elements. Set operations like union, intersection, and difference are lightning fast.
Use sets for fast membership testing and deduplication. For ordered unique items, use dict.fromkeys() to preserve insertion order.
๐ป Code Example:
# 1. Creating sets pynfinity_courses = {'Python', 'AI', 'DevOps', 'Testing', 'Java'} santoshtvk_completed = {'Python', 'AI', 'JavaScript'} # 2. Core set operations union = pynfinity_courses | santoshtvk_completed # All items from both intersection = pynfinity_courses & santoshtvk_completed # Common items difference = pynfinity_courses - santoshtvk_completed # In pynfinity but NOT completed sym_diff = pynfinity_courses ^ santoshtvk_completed # Unique to each set print("All courses:", union) print("Completed Pynfinity courses:", intersection) print("Remaining to complete:", difference) # 3. Membership testing โ O(1) lookup! print('Python' in pynfinity_courses) # True (fast O(1)) print('PHP' not in pynfinity_courses) # True # 4. Remove duplicates from a list raw_visitors = ['tvk', 'dhruv', 'tvk', 'santoshtvk', 'dhruv', 'tvk'] unique_visitors = list(set(raw_visitors)) # Order NOT guaranteed print(f"Unique visitors: {len(unique_visitors)}") # 5. Frozen set โ immutable set (hashable, can be dict key) admin_emails = frozenset({'admin@pynfinity.com', 'santoshtvk@pynfinity.com'}) # admin_emails.add(...) # AttributeError โ immutable! # 6. Set comprehension squares_set = {x**2 for x in range(10)} print(squares_set)
| Concept | Key Takeaway |
|---|---|
| | (union) | All elements from both sets |
| & (intersection) | Elements in BOTH sets |
| - (difference) | In first but not in second |
| ^ (symmetric diff) | In one OR the other but not BOTH |
| .add() / .discard() | Add or remove a single element |
Keep exploring and happy coding! ๐