Python Set Methods
Table of Contents
In the last lesson, we learned about Python Set Difference. Now let’s use built-in set methods to add, remove, update, and compare items.
Let’s Talk About Tools for Sets
We know what a set is. It is an unordered collection of unique items.
We know how to create one. We know how to loop through it. We know about set operations like union, intersection, and difference.
Now let’s talk about set methods. These are built-in functions that belong to set objects. They let us add items, remove items, update the set, and more.
Let’s remember, sets are mutable. So most methods change the set in place. They do not return a new set. They modify the original.
Let’s go through the most common ones.
Adding Items to a Python Set
add()
Adds a single item to the set.
fruits = {"apple", "banana"}fruits.add("orange")print(fruits)Output
{'apple', 'banana', 'orange'}If the item already exists, nothing happens. No error.
fruits.add("apple")print(fruits)Output
{'apple', 'banana', 'orange'}Still the same set. Because sets don’t allow duplicates.
update()
Adds multiple items to the set. We can pass another set, a list, a tuple, or any iterable.
fruits = {"apple", "banana"}fruits.update(["orange", "grape"])print(fruits)Output
{'apple', 'banana', 'orange', 'grape'}We can also pass multiple iterables.
fruits.update(["kiwi"], ["mango"])print(fruits)Output
{'apple', 'banana', 'orange', 'grape', 'kiwi', 'mango'}Duplicates are ignored.
Removing Items from a Python Set
remove()
Removes a specific item. If the item is not found, it raises a KeyError.
fruits = {"apple", "banana", "orange"}fruits.remove("banana")print(fruits)Output
{'apple', 'orange'}fruits.remove("grape") # Error!Output
KeyError: 'grape'So let’s only use remove() if we are sure the item exists.
discard()
Removes a specific item. If the item is not found, it does nothing. No error.
fruits = {"apple", "banana", "orange"}fruits.discard("banana")print(fruits)Output
{'apple', 'orange'}fruits.discard("grape") # No errorprint(fruits)Output
{'apple', 'orange'}discard() is safer. Let’s use it when we are not sure if the item is there.
pop()
Removes and returns an arbitrary item from the set. Because sets are unordered, we do not know which item will be removed.
fruits = {"apple", "banana", "orange"}removed = fruits.pop()print(removed)print(fruits)Output (may vary):
banana{'apple', 'orange'}If the set is empty, pop() raises a KeyError.
empty = set()empty.pop() # Error!clear()
Removes all items from the set. The set becomes empty.
fruits = {"apple", "banana", "orange"}fruits.clear()print(fruits)Output
set()Copying a Python Set
copy()
Returns a shallow copy of the set.
original = {1, 2, 3}copied = original.copy()print(copied)Output
{1, 2, 3}Now copied is a separate set. Changing one does not affect the other.
Set Operations as Methods in Python
We already covered union, intersection, and difference in earlier articles. But they are also methods. Let’s list them here for completeness.
union()
Returns a new set with all items from both sets.
set1 = {1, 2}set2 = {2, 3}print(set1.union(set2))Output
{1, 2, 3}intersection()
Returns a new set with only the common items.
set1 = {1, 2, 3}set2 = {2, 3, 4}print(set1.intersection(set2))Output
{2, 3}difference()
Returns a new set with items in the first set but not the second.
set1 = {1, 2, 3}set2 = {2, 3, 4}print(set1.difference(set2))Output
{1}symmetric_difference()
Returns a new set with items in either set but not both.
set1 = {1, 2, 3}set2 = {2, 3, 4}print(set1.symmetric_difference(set2))Output
{1, 4}In-Place Update Methods in Python
These methods modify the set in place. They do not return a new set.
update()
We already saw this. It adds items from another iterable.
intersection_update()
Keeps only the items that are in both sets.
set1 = {1, 2, 3, 4}set2 = {3, 4, 5}set1.intersection_update(set2)print(set1)Output
{3, 4}difference_update()
Removes items that are in another set.
set1 = {1, 2, 3, 4}set2 = {3, 4, 5}set1.difference_update(set2)print(set1)Output
{1, 2}symmetric_difference_update()
Keeps only the items that are in one set or the other, but not both.
set1 = {1, 2, 3}set2 = {3, 4, 5}set1.symmetric_difference_update(set2)print(set1)Output
{1, 2, 4, 5}Checking Relationships in Python Sets
issubset()
Checks if all items of one set are in another.
set1 = {1, 2}set2 = {1, 2, 3, 4}print(set1.issubset(set2))Output
Trueissuperset()
Checks if one set contains all items of another.
set1 = {1, 2, 3, 4}set2 = {1, 2}print(set1.issuperset(set2))Output
Trueisdisjoint()
Checks if two sets have no items in common.
set1 = {1, 2}set2 = {3, 4}print(set1.isdisjoint(set2))Output
TrueIf they share at least one item, it returns False.
set1 = {1, 2}set2 = {2, 3}print(set1.isdisjoint(set2))Output
FalsePython Set Methods: A Real-Life Example
Let’s build a simple program that manages a set of tags for a blog post.
tags = {"python", "coding"}
# Add a tagtags.add("beginner")print(tags)
# Add multiple tagstags.update(["tutorial", "programming"])print(tags)
# Remove a tagtags.discard("coding")print(tags)
# Check if a tag existsif "python" in tags: print("Python tag is present")
# Clear all tagstags.clear()print(tags)Output
{'python', 'coding', 'beginner'}{'python', 'coding', 'beginner', 'tutorial', 'programming'}{'python', 'beginner', 'tutorial', 'programming'}Python tag is presentset()That uses add(), update(), discard(), in, and clear().
Common Mistakes with Python Set Methods
Mistake 1: Using remove() Without Checking
fruits = {"apple"}fruits.remove("banana") # Error!So what do we do? We use discard() instead.
fruits.discard("banana")Mistake 2: Thinking update() Returns a New Set
set1 = {1, 2}set1 = set1.update([3, 4]) # set1 becomes Noneprint(set1)Output
NoneBecause update() changes the set in place and returns None. Let’s not assign the result.
So what do we do? We just call it.
set1.update([3, 4])print(set1)Mistake 3: Forgetting That pop() Is Arbitrary
fruits = {"apple", "banana", "orange"}removed = fruits.pop()print(removed)We do not know which item will be removed. Let’s not rely on it.
Mistake 4: Using the Wrong Method Name
set1 = {1, 2}set1.add_all([3, 4]) # Error! No such methodSo what do we do? We use update().
set1.update([3, 4])Next, we will learn about Python Dictionaries and store values using descriptive keys.