๐ Python# 5: Sets โ Fast, Unique & Unordered
A set is an unordered, mutable collection of unique elements.
๐ง Syntax:
fruits = {"apple", "banana", "cherry"}
empty_set = set() # NOT {} (thatโs a dict!)
โ
Key Features:
โขUnordered: No indexing
โขNo duplicates allowed
โขMutable: Can add/remove items
โขExtremely fast membership tests
๐ ๏ธ Core Methods:
s.add("mango") # Add item
s.update(["grape", "kiwi"]) # Add multiple
s.remove("apple") # Remove item (KeyError if not found)
s.discard("pear") # Remove if exists (no error)
s.pop() # Remove random element
s.clear() # Empty the set
๐ Set Operations:
a = {1, 2, 3}
b = {3, 4, 5}
a.union(b) # {1, 2, 3, 4, 5}
a.intersection(b) # {3}
a.difference(b) # {1, 2}
a.symmetric_difference(b) # {1, 2, 4, 5}
a.isdisjoint(b) # False
a.issubset(b) # False
a.issuperset(b) # False
๐ Real-World Use Case:
โ๏ธ Removing duplicates from a list:
emails = ["a@x.com", "b@x.com", "a@x.com"]
unique_emails = set(emails)
โ๏ธ Fast membership test:
blacklist = {"spamdotcom", "fakedotcom"}
if domain in blacklist:
block_request()
โก Performance Tip:
set membership: O(1) โ much faster than lists (O(n))
Ideal for deduplication, lookup-heavy tasks
๐ก Interview Insight:
Q: When would you use a set instead of a list?
A: When uniqueness and fast membership testing matter. For example, checking if a user has already visited a page.
Bonus ๐ก: Convert back to list if needed as shown below:
unique_list = list(set(my_list))
โ
๐ Coming up next: Dicts in Python โ Keys, Values, and Fast Lookups
#Python #PythonTips #100DaysOfCode #LearnToCode #DevCommunity #PythonBeginners #CodingInterview #DataStructures #SetOperations