Member-only story
Master Python Sets: Tips, Tricks, and Best Practices
Learn the power of Python sets for managing unique items. Get tips, tricks, and practical examples to improve your coding efficiency
What is set in Python?
Set: A Python set is an unordered collection of unique elements.
_set = {"apple"}
_set = set()
_not_set = {}Removing element:
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana") # discard() will not raise an error.
fruits.remove("banana") # Raises KeyError if "banana" is not in the set
print(fruits) # Output: {'apple', 'cherry'}Removing Duplicates from a List using a Set:
fruits = ["apple", "banana", "cherry", "apple", "banana", "cherry", "kiwi"]
unique_items = list(set(fruits)) # Output: ["apple", "banana", "cherry", "kiwi"]Set operations:
0. Joining two sets:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1) # Output: {1, 2, 3, 'b', 'c', 'a'}
# Or
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 'b', 'c', 'a'}- Common elements between two sets:









