Sets
Work with unique collections
Today, we're going to explore sets, a really useful data structure in Python for handling unique items.
What are sets?
Imagine a collection of items where every item is distinct. That's exactly what a set is! No duplicates allowed. Sets are also unordered, meaning the items don't have a specific position or index.
- Sets only store unique elements.
- Items in a set do not have a defined order.
- Sets are mutable, so you can add or remove elements after creation.
Creating sets
You can create a set by listing items inside curly braces or by using the set() constructor. Remember, duplicate values will automatically be removed.
my_set = {1, 2, 3, 2}
print(my_set) # Output: {1, 2, 3}
also_a_set = set(['a', 'b', 'c', 'a'])
print(also_a_set) # Output: {'a', 'b', 'c'}
empty_set = set() # This is how you create an empty set
print(empty_set) # Output: set()Basic operations
Sets support many operations to manipulate their contents or compare them with other sets. Here are a few common ones.
fruits = {'apple', 'banana', 'cherry'}
# Adding an element
fruits.add('orange')
print(fruits) # Output might be {'apple', 'orange', 'banana', 'cherry'}
# Trying to add a duplicate (does nothing)
fruits.add('apple')
print(fruits) # Output is still the same as above
# Removing an element
fruits.remove('banana')
print(fruits) # Output might be {'apple', 'orange', 'cherry'}
# Checking if an element is in the set
print('apple' in fruits) # Output: True
print('grape' in fruits) # Output: FalseCommon uses
Sets shine in situations where uniqueness and quick lookups are key.
Remove duplicates
One of the most frequent uses for sets is to easily get rid of duplicate items from a list or other iterable. Just convert it to a set and back to a list!
numbers_with_duplicates = [1, 2, 2, 3, 4, 1, 5, 3]
unique_numbers = list(set(numbers_with_duplicates))
print(unique_numbers) # Output: [1, 2, 3, 4, 5] (order might vary)Fast membership testing
Checking if an item is present in a large collection is much faster with sets than with lists. This is because of how sets are designed internally.
import time
large_list = list(range(1_000_000))
large_set = set(large_list)
start_time = time.time()
1_000_000 in large_list
end_time = time.time()
print(f"List lookup: {end_time - start_time:.6f} seconds")
start_time = time.time()
1_000_000 in large_set
end_time = time.time()
print(f"Set lookup: {end_time - start_time:.6f} seconds")Common mistakes
- Mutable elements: You cannot add mutable objects (like lists or other sets) directly into a set. Only immutable objects (numbers, strings, tuples) can be set members.
- Order assumption: Don't rely on sets to keep items in the order you added them. If order matters, use a list.
- Empty set: Remember
set()for an empty set, not.
my_bad_set = {[1, 2], 'hello'} # This will raise a TypeError!Practice
Try these exercises to lock in what you just learned.
What's next?
Now that you understand the basics of sets, try exploring more of their unique operations like union(), intersection(), difference(), and symmetric_difference(). These are incredibly powerful for comparing and combining collections of unique items!
Keep practicing by solving small problems that involve unique data or needing fast membership checks.
Next, you'll combine lists and dictionaries into nested data, the shape most real-world data takes.