Sets are unordered collections of unique elements — perfect for membership testing and deduplication.
Python Sets
Sets store unique elements with no duplicates and no guaranteed order. They are ideal for membership testing and set operations (union, intersection, difference).
Syntax
<pre><code># Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 3, 2, 1} # Duplicates removed
print(numbers) # {1, 2, 3}
empty_set = set() # NOT {} (that creates a dict!)
# Adding/Removing
fruits.add("mango")
fruits.discard("banana") # No error if not found
fruits.remove("cherry") # Raises KeyError if not found
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric difference: {1, 2, 5, 6}
# Fast membership testing O(1)
print("apple" in fruits) # True
# Remove duplicates from a list
duplicates = [1, 2, 2, 3, 3, 3]
unique = list(set(duplicates)) # [1, 2, 3]
</code></pre>
Revision Notes
• {} for sets; set() for empty set
• No duplicates; unordered
• add(), discard() (safe), remove() (raises error)
• |=union, &=intersection, -=difference, ^=symmetric
• O(1) membership testing (much faster than lists)
Write a function unique_words(text) that takes a string of words separated by spaces and returns the count of unique words (case-insensitive), using a set.
Input:
"the cat sat on the mat the cat ran"
Output:
5
Show Hint
Lowercase the string, split on spaces, and convert to a set to remove duplicates.