Python Set Methods
Python's built-in set methods allow you to perform various operations on sets, such as adding elements, finding unions and intersections, and removing items. These methods make it easy to manipulate unordered collections of unique elements.
Here are some commonly used set methods:
- add(): Adds a specified element to the set.
- update(): Updates the set with elements from another iterable.
- remove(): Removes the specified element. Raises an error if the element is not present.
- discard(): Removes the specified element without raising an error if it is not found.
- pop(): Removes and returns an arbitrary element from the set.
- clear(): Removes all elements from the set.
- union(): Returns a new set containing all unique elements from the original and the specified sets.
- intersection(): Returns a new set containing elements common to both sets.
- difference(): Returns a new set with elements in the original set but not in the other.
- issubset(): Checks whether all elements of the set are present in another set.
- issuperset(): Checks whether the set contains all elements of another set.
Adding Elements to a Set
Python sets are mutable, meaning you can add new elements after the set is created. There are two primary methods for adding elements to a set:
- add() – Adds a single specified element to the set. If the element already exists, the set remains unchanged.
- update() – Adds multiple elements to the set from an iterable (e.g., list, tuple, or another set).
Example 1: Using add() to Add a Single Element
The add() method inserts a single element into the set. Duplicate values are ignored since sets only store unique elements.
planets = {"earth", "mars"}
planets.add("Neptune")
planets.add("earth") # "earth" is already in the set
print(planets)
planets = {"earth", "mars"}
planets.add("Neptune")
planets.add("earth") # "earth" is already in the set
print(planets)
How It Works:
- planets: A set initially containing "earth" and "mars".
- add("Neptune"): Inserts a new element into the set.
- add("earth"): Has no effect since "earth" is already present.
- Sets do not allow duplicates, so each element is stored only once.
Output (order may vary)
{'mars', 'Neptune', 'earth'}
{'mars', 'Neptune', 'earth'}
Example 2: Using update() to Add Multiple Elements
The update() method allows you to add multiple items from an iterable like a list, tuple, or another set.
colors = {"red", "blue"}
colors.update(["green", "yellow"])
colors.update({"purple", "blue"}) # "blue" is already present
print(colors)
colors = {"red", "blue"}
colors.update(["green", "yellow"])
colors.update({"purple", "blue"}) # "blue" is already present
print(colors)
How It Works:
- colors: Starts with two elements.
- update([...]): Adds all elements from the given list or set.
- Duplicates (like "blue") are ignored.
Output (order may vary)
{'red', 'blue', 'green', 'yellow', 'purple'}
{'red', 'blue', 'green', 'yellow', 'purple'}
Removing Elements from a Set
Python provides several methods to remove elements from a set. Each method behaves differently, especially when the element to be removed might not exist:
- remove() – Removes a specified element from the set. Raises a KeyError if the element is not found.
- discard() – Removes a specified element if it exists. Does nothing if the element is not found.
- pop() – Removes and returns an arbitrary element from the set. Raises KeyError if the set is empty.
- clear() – Removes all elements from the set, leaving it empty.
Example 1: Using remove() and discard()
Both remove() and discard() can be used to delete elements, but only remove() throws an error if the element is missing.
numbers = {1, 2, 3, 4}
numbers.remove(2)
numbers.discard(3)
# numbers.remove(10) # This would raise a KeyError
numbers.discard(10) # Safe, does nothing
print(numbers)
numbers = {1, 2, 3, 4}
numbers.remove(2)
numbers.discard(3)
# numbers.remove(10) # This would raise a KeyError
numbers.discard(10) # Safe, does nothing
print(numbers)
How It Works:
- remove(2): Deletes 2 from the set.
- discard(3): Deletes 3 from the set.
- remove(10): Would raise a KeyError (commented out in the example).
- discard(10): Does nothing because 10 is not in the set.
Output
{1, 4}
{1, 4}
Example 2: Using pop() and clear()
The pop() method removes and returns a random element. clear() empties the entire set.
colors = {"red", "green", "blue"}
removed = colors.pop() # Randomly removes one item
print("Removed:", removed)
colors.clear() # Empties the set
print(colors)
colors = {"red", "green", "blue"}
removed = colors.pop() # Randomly removes one item
print("Removed:", removed)
colors.clear() # Empties the set
print(colors)
How It Works:
- pop(): Removes an arbitrary item and returns it. The item removed is not predictable.
- clear(): Removes all elements, leaving an empty set.
Sample Output
Removed: blue
set()
Removed: blue
set()
Set Operations in Python
Python sets support powerful mathematical operations that help you compare and combine collections. These methods return new sets and do not modify the original sets unless assigned.
- union() – Returns a new set containing all unique elements from both sets.
- intersection() – Returns a set containing elements common to both sets.
- difference() – Returns a set with elements that are in the first set but not in the second.
Example 1: Using union() to Combine Sets
The union() method returns a new set that includes every unique element from both sets.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
result = set_a.union(set_b)
print(result)
set_a = {1, 2, 3}
set_b = {3, 4, 5}
result = set_a.union(set_b)
print(result)
How It Works:
- set_a: A set containing 1, 2, and 3.
- set_b: A set containing 3, 4, and 5.
- union(set_b): Combines both sets, returning all unique elements.
- The resulting set contains all elements from both sets without duplicates.
Output (order may vary)
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
Example 2: Using intersection() to Find Common Elements
The intersection() method returns elements that exist in both sets.
set_a = {"earth", "mars", "jupiter"}
set_b = {"mars", "jupiter", "neptune"}
result = set_a.intersection(set_b)
print(result)
set_a = {"earth", "mars", "jupiter"}
set_b = {"mars", "jupiter", "neptune"}
result = set_a.intersection(set_b)
print(result)
How It Works:
- set_a: A set containing "earth", "mars", and "jupiter".
- set_b: A set containing "mars", "jupiter", and "neptune".
- intersection(set_b): Finds elements common to both sets.
- The resulting set contains only elements present in both sets.
Output (order may vary)
{'mars', 'jupiter'}
{'mars', 'jupiter'}
Example 3: Using difference() to Find Unique Elements
The difference() method returns elements that are in the first set but not in the second.
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5}
result = set_a.difference(set_b)
print(result)
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5}
result = set_a.difference(set_b)
print(result)
How It Works:
- set_a: A set containing 1, 2, 3, and 4.
- set_b: A set containing 3, 4, and 5.
- difference(set_b): Returns elements in set_a that are not in set_b.
- The resulting set contains only unique elements from set_a.
Output (order may vary)
{1, 2}
{1, 2}
Membership Checks in Sets
Python sets support methods that allow you to compare sets and test for subset, superset, or disjoint relationships. These are useful for checking how sets relate to one another.
- issubset() – Returns True if all elements of the set are present in another set.
- issuperset() – Returns True if the set contains all elements of another set.
- isdisjoint() – Returns True if the two sets have no elements in common.
Example 1: Using issubset() to Check Subset Relationship
The issubset() method checks whether all elements of one set exist within another set.
a = {1, 2}
b = {1, 2, 3, 4}
print(a.issubset(b)) # True
print(b.issubset(a)) # False
a = {1, 2}
b = {1, 2, 3, 4}
print(a.issubset(b)) # True
print(b.issubset(a)) # False
How It Works:
- a: A set containing 1 and 2.
- b: A set containing 1, 2, 3, and 4.
- a.issubset(b): Returns True because all elements in a are in b.
- b.issubset(a): Returns False because b contains elements not in a.
Output
True
False
True
False
Example 2: Using issuperset() to Check Superset Relationship
The issuperset() method checks whether the set includes all elements from another set.
a = {1, 2, 3, 4}
b = {2, 3}
print(a.issuperset(b)) # True
print(b.issuperset(a)) # False
a = {1, 2, 3, 4}
b = {2, 3}
print(a.issuperset(b)) # True
print(b.issuperset(a)) # False
How It Works:
- a: A set containing 1, 2, 3, and 4.
- b: A set containing 2 and 3.
- a.issuperset(b): Returns True because a contains all elements of b.
- b.issuperset(a): Returns False because b does not contain all elements of a.
Output
True
False
True
False
Example 3: Using isdisjoint() to Check for No Common Elements
The isdisjoint() method checks whether two sets share no elements in common.
a = {1, 2}
b = {3, 4}
c = {2, 5}
print(a.isdisjoint(b)) # True
print(a.isdisjoint(c)) # False
a = {1, 2}
b = {3, 4}
c = {2, 5}
print(a.isdisjoint(b)) # True
print(a.isdisjoint(c)) # False
How It Works:
- a: A set containing 1 and 2.
- b: A set containing 3 and 4.
- c: A set containing 2 and 5.
- a.isdisjoint(b): Returns True because a and b share no elements.
- a.isdisjoint(c): Returns False because a and c share the element 2.
Output
True
False
True
False
Copying Sets in Python
When working with sets, you may want to create a copy to preserve the original while performing operations on the duplicate. Python provides the copy() method to create a shallow copy of a set.
- copy() – Returns a new set that is a shallow copy of the original set. The original set remains unchanged.
Example: Using copy() to Duplicate a Set
The copy() method allows you to create a duplicate of a set so that changes made to the new set do not affect the original.
original = {"earth", "mars", "jupiter"}
copied = original.copy()
copied.add("Saturn")
print("Original:", original)
print("Copied:", copied)
original = {"earth", "mars", "jupiter"}
copied = original.copy()
copied.add("Saturn")
print("Original:", original)
print("Copied:", copied)
How It Works:
- original: A set containing "earth", "mars", and "jupiter".
- copy(): Creates a new set copied that duplicates original.
- copied.add("Saturn"): Adds "Saturn" to the copied set only.
- The original set remains unchanged, showing that copy() creates an independent copy.
Output (order may vary)
Original: {'earth', 'mars', 'jupiter'}
Copied: {'earth', 'mars', 'jupiter', 'Saturn'}
Original: {'earth', 'mars', 'jupiter'}
Copied: {'earth', 'mars', 'jupiter', 'Saturn'}
Frequently Asked Questions
What are some common set methods in Python?
What are some common set methods in Python?
Common methods include add(), remove(), discard(), pop(), clear(), union(), intersection(), difference(), and update().
What is the difference between remove() and discard()?
What is the difference between remove() and discard()?
remove() will raise a KeyError if the element is not present in the set, while discard() will not raise any error if the element is missing.
How do I add elements to a set?
How do I add elements to a set?
Use add() to add a single element, or update() to add multiple elements from another iterable like lists or sets.
Can I modify a set while iterating over it?
Can I modify a set while iterating over it?
Modifying a set during iteration is not recommended as it can cause runtime errors or unexpected behavior.
How do I create a shallow copy of a set?
How do I create a shallow copy of a set?
Use the copy() method to create a shallow copy of a set.
What's Next?
Up next, you'll learn how to use the input() function to get user input in Python—an essential tool for making your programs interactive.