- add() — add elements to a set
- remove() — remove elements by value
- discard() — safely remove elements
- pop() — remove and return arbitrary element
- clear() — remove all elements
- union() — combine sets
- intersection() — common elements
- difference() — elements in one set only
- symmetric_difference() — elements in either set
- update() — in-place union
Introduction to Set Methods
Python sets provide a rich collection of methods for manipulating set data. These methods can be grouped into several categories:
- Adding methods:
add(),update() - Removing methods:
remove(),discard(),pop(),clear() - Set operations:
union(),intersection(),difference(),symmetric_difference() - Set relationships:
issubset(),issuperset(),isdisjoint()
Most set methods modify the set in place, meaning they change the original set rather than creating a new one.
💡 Key concept: Many set methods have both in-place versions (modifying the original set) and operator equivalents (|, &, -, ^) that return new sets.
add() — Add Elements
Adding a Single Element
The add() method adds a single element to the set. If the element already exists, it has no effect.
# Basic usage
fruits = {"apple", "banana", "cherry"}
print(fruits) # {'apple', 'banana', 'cherry'}
fruits.add("mango")
print(fruits) # {'apple', 'banana', 'cherry', 'mango'}
# Adding an existing element (no effect)
fruits.add("apple")
print(fruits) # {'apple', 'banana', 'cherry', 'mango'}
# Adding different data types
numbers = {1, 2, 3}
numbers.add(4) # Integer
numbers.add("five") # String
numbers.add((6, 7)) # Tuple
print(numbers) # {1, 2, 3, 4, 'five', (6, 7)}
# Adding in a loop
squares = set()
for i in range(5):
squares.add(i ** 2)
print(squares) # {0, 1, 4, 9, 16}
Characteristics:
- Adds a single element to the set
- Modifies the set in place (returns
None) - Has no effect if the element already exists
- Element must be hashable (immutable)
- Time complexity: O(1) on average
Quick Check: What happens if you add an element that already exists in the set? (Answer: Nothing — the set remains unchanged)
remove() — Delete by Value
Removing a Specific Element
The remove() method removes a specified element from the set. If the element is not found, it raises a KeyError.
# Basic usage
fruits = {"apple", "banana", "cherry", "mango"}
print(fruits) # {'apple', 'banana', 'cherry', 'mango'}
fruits.remove("banana")
print(fruits) # {'apple', 'cherry', 'mango'}
# Attempting to remove a non-existent element
# fruits.remove("grape") # KeyError: 'grape'
# Safe approach — check first
if "grape" in fruits:
fruits.remove("grape")
else:
print("'grape' not in set")
# Removing in a loop
numbers = {1, 2, 3, 4, 5, 6}
for num in list(numbers): # Iterate over a copy
if num % 2 == 0:
numbers.remove(num)
print(numbers) # {1, 3, 5}
Characteristics:
- Removes the specified element
- Raises
KeyErrorif the element is not found - Modifies the set in place
- Time complexity: O(1) on average
Quick Check: What happens if you try to remove an element that doesn't exist? (Answer: KeyError is raised)
discard() — Safe Removal
Removing Without Raising Errors
The discard() method removes a specified element from the set. Unlike remove(), it does nothing if the element is not found.
# Basic usage
fruits = {"apple", "banana", "cherry", "mango"}
print(fruits) # {'apple', 'banana', 'cherry', 'mango'}
fruits.discard("banana")
print(fruits) # {'apple', 'cherry', 'mango'}
# Discarding a non-existent element (no error)
fruits.discard("grape")
print(fruits) # {'apple', 'cherry', 'mango'}
# Discarding in a loop
numbers = {1, 2, 3, 4, 5, 6}
for num in list(numbers):
if num % 2 == 0:
numbers.discard(num)
print(numbers) # {1, 3, 5}
Characteristics:
- Removes the specified element if present
- Does nothing if the element is not found
- No error is raised
- Modifies the set in place
- Time complexity: O(1) on average
Quick Check: What is the difference between remove() and discard()? (Answer: discard() does nothing if the element is not found; remove() raises KeyError)
pop() — Remove and Return
Removing an Arbitrary Element
The pop() method removes and returns an arbitrary element from the set. Since sets are unordered, you cannot predict which element will be removed.
# Basic usage
fruits = {"apple", "banana", "cherry", "mango"}
print(f"Original: {fruits}")
removed = fruits.pop()
print(f"Removed: {removed}")
print(f"After pop: {fruits}")
# Popping in a loop (removes all elements)
numbers = {1, 2, 3, 4, 5}
while numbers:
element = numbers.pop()
print(f"Removed: {element}")
print(f"Empty set: {numbers}")
# Safe usage — check before popping
fruits = {"apple", "banana", "cherry"}
if fruits:
element = fruits.pop()
print(f"Removed: {element}")
else:
print("Set is empty")
# pop() cannot be called with an argument
# fruits.pop("apple") # TypeError: set.pop() takes no arguments (1 given)
Characteristics:
- Removes and returns an arbitrary element
- Raises
KeyErrorif the set is empty - Modifies the set in place
- Time complexity: O(1) on average
- Useful for processing all elements
Quick Check: What happens if you call pop() on an empty set? (Answer: KeyError is raised)
clear() — Remove All
Removing All Elements
The clear() method removes all elements from the set, leaving it empty.
# Basic usage
fruits = {"apple", "banana", "cherry", "mango"}
print(f"Before clear: {fruits}")
fruits.clear()
print(f"After clear: {fruits}") # set()
# Checking if set is empty after clear
if not fruits:
print("Set is empty")
# Clearing in a loop
numbers = {1, 2, 3, 4, 5}
for num in list(numbers):
numbers.remove(num)
print(numbers) # set()
# Alternative: reassign to empty set
numbers = {1, 2, 3, 4, 5}
numbers = set() # Creates a new empty set
Characteristics:
- Removes all elements from the set
- Modifies the set in place
- Time complexity: O(n)
- Useful for resetting a set
Quick Check: What does clear() return? (Answer: None — it modifies the set in place)
union() — Combine Sets
Combining Sets
The union() method returns a new set containing all elements from the original set and the specified set(s). The | operator provides the same functionality.
# Basic usage
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Using union() method
result = set1.union(set2)
print(result) # {1, 2, 3, 4, 5, 6, 7, 8}
# Using operator
result = set1 | set2
print(result) # {1, 2, 3, 4, 5, 6, 7, 8}
# Original sets unchanged
print(set1) # {1, 2, 3, 4, 5}
print(set2) # {4, 5, 6, 7, 8}
# Union with multiple sets
set3 = {7, 8, 9, 10}
result = set1.union(set2, set3)
print(result) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
# Union with a list (any iterable)
list1 = [11, 12, 13]
result = set1.union(list1)
print(result) # {1, 2, 3, 4, 5, 11, 12, 13}
Characteristics:
- Returns a new set (does not modify original)
- Accepts multiple iterables as arguments
- Operator equivalent:
| - Time complexity: O(len(s) + len(t))
Quick Check: Does union() modify the original set? (Answer: No — it returns a new set)
intersection() — Common Elements
Finding Common Elements
The intersection() method returns a new set containing elements that are present in both the original set and the specified set(s). The & operator provides the same functionality.
# Basic usage
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Using intersection() method
result = set1.intersection(set2)
print(result) # {4, 5}
# Using operator
result = set1 & set2
print(result) # {4, 5}
# Intersection with multiple sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
set3 = {4, 5, 8, 9, 10}
result = set1.intersection(set2, set3)
print(result) # {4, 5}
# Intersection with a list
list1 = [3, 4, 5]
result = set1.intersection(list1)
print(result) # {3, 4, 5}
Characteristics:
- Returns a new set (does not modify original)
- Accepts multiple iterables as arguments
- Operator equivalent:
& - Time complexity: O(min(len(s), len(t)))
Quick Check: Which operation returns elements common to both sets? (Answer: intersection() or &)
difference() — Elements in One Set Only
Finding Elements Unique to One Set
The difference() method returns a new set containing elements that are in the original set but not in the specified set(s). The - operator provides the same functionality.
# Basic usage
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Using difference() method
result = set1.difference(set2)
print(result) # {1, 2, 3}
# Using operator
result = set1 - set2
print(result) # {1, 2, 3}
# Difference with multiple sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5}
set3 = {5, 6, 7}
result = set1.difference(set2, set3)
print(result) # {1, 2}
# Difference with a list
list1 = [3, 4, 5]
result = set1.difference(list1)
print(result) # {1, 2}
Characteristics:
- Returns a new set (does not modify original)
- Accepts multiple iterables as arguments
- Operator equivalent:
- - Time complexity: O(len(s))
Quick Check: What does set1 - set2 return? (Answer: Elements in set1 but not in set2)
symmetric_difference() — Elements in Either Set
Finding Elements in Either Set (Not Both)
The symmetric_difference() method returns a new set containing elements that are in either the original set or the specified set, but not in both. The ^ operator provides the same functionality.
# Basic usage
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Using symmetric_difference() method
result = set1.symmetric_difference(set2)
print(result) # {1, 2, 3, 6, 7, 8}
# Using operator
result = set1 ^ set2
print(result) # {1, 2, 3, 6, 7, 8}
# Symmetric difference with a list
list1 = [4, 5, 6]
result = set1.symmetric_difference(list1)
print(result) # {1, 2, 3, 6}
Characteristics:
- Returns a new set (does not modify original)
- Accepts one iterable as argument
- Operator equivalent:
^ - Time complexity: O(len(s) + len(t))
Quick Check: What does symmetric_difference() return? (Answer: Elements in either set but not in both)
update() — In-Place Union
Adding Multiple Elements In Place
The update() method adds all elements from another iterable to the set. It modifies the set in place. This is the in-place version of union().
# Basic usage
set1 = {1, 2, 3}
set2 = {4, 5, 6}
set1.update(set2)
print(set1) # {1, 2, 3, 4, 5, 6}
# Updating with a list
fruits = {"apple", "banana"}
fruits.update(["cherry", "mango", "orange"])
print(fruits) # {'apple', 'banana', 'cherry', 'mango', 'orange'}
# Updating with multiple iterables
set1 = {1, 2, 3}
set1.update([4, 5], {6, 7}, (8, 9))
print(set1) # {1, 2, 3, 4, 5, 6, 7, 8, 9}
# Updating with a string (adds each character)
letters = {'a', 'b'}
letters.update('cd')
print(letters) # {'a', 'b', 'c', 'd'}
Characteristics:
- Modifies the set in place
- Accepts multiple iterables as arguments
- Equivalent to
|operator but modifies in place - Time complexity: O(len(iterable))
Quick Check: What is the difference between union() and update()? (Answer: union() returns a new set; update() modifies the set in place)
Common Mistakes
Watch Out For These!
Mistake 1: Using remove() Without Checking Existence
# WRONG — raises KeyError if element not found
fruits = {"apple", "banana", "cherry"}
# fruits.remove("grape") # KeyError
# CORRECT — check first
if "grape" in fruits:
fruits.remove("grape")
else:
print("Element not found")
# CORRECT — use discard() instead
fruits.discard("grape") # No error
Mistake 2: Confusing update() with add()
# WRONG — add() adds the entire list as one element
fruits = {"apple", "banana"}
fruits.add(["cherry", "mango"]) # TypeError
# WRONG — using add() with multiple elements
# fruits.add("cherry", "mango") # TypeError
# CORRECT — use update() for multiple elements
fruits.update(["cherry", "mango"])
print(fruits) # {'apple', 'banana', 'cherry', 'mango'}
Mistake 3: Using pop() on an Empty Set
# WRONG — raises KeyError
empty_set = set()
# empty_set.pop() # KeyError
# CORRECT — check before popping
if empty_set:
element = empty_set.pop()
else:
print("Set is empty")
Mistake 4: Modifying a Set While Iterating
# WRONG — modifies set during iteration
numbers = {1, 2, 3, 4, 5}
# for num in numbers:
# if num % 2 == 0:
# numbers.remove(num) # RuntimeError
# CORRECT — iterate over a copy
for num in list(numbers):
if num % 2 == 0:
numbers.remove(num)
print(numbers) # {1, 3, 5}
Quick Check: What is the difference between remove() and discard()? (Answer: remove() raises KeyError if not found; discard() does nothing)
Interactive Editor
Experiment with set methods directly in your browser. Modify the code and see the results in real time.
SET METHODS PRACTICE
========================================
Fruits: {'apple', 'banana', 'cherry'}
Numbers1: {1, 2, 3, 4, 5}
Numbers2: {4, 5, 6, 7, 8}
1. ADD()
After add: {'apple', 'banana', 'cherry', 'mango'}
2. REMOVE()
After remove: {'apple', 'cherry', 'mango'}
3. DISCARD()
After discard: {'cherry', 'mango'}
4. POP()
Removed: cherry
After pop: {'mango'}
5. UNION()
Union: {1, 2, 3, 4, 5, 6, 7, 8}
6. INTERSECTION()
Intersection: {4, 5}
7. DIFFERENCE()
Difference (numbers1 - numbers2): {1, 2, 3}
8. SYMMETRIC_DIFFERENCE()
Symmetric difference: {1, 2, 3, 6, 7, 8}
9. UPDATE()
After update: {1, 2, 3, 4, 5, 9, 10}
10. CLEAR()
After clear: set()
Set methods practice complete!
Certificate of Completion
You have completed the Python Set Methods tutorial. You understand add, remove, discard, pop, clear, union, intersection, difference, symmetric_difference, and update methods.
Quick Quiz — Test Your Knowledge
Let's see what you've learned about set methods:
Frequently Asked Questions
What is the difference between remove() and discard()?
remove() raises a KeyError if the element is not found. discard() does nothing if the element is not found. Use discard() when you want to safely remove an element without checking if it exists.
What is the difference between union() and update()?
union() returns a new set containing all elements from both sets. update() modifies the original set in place. Use union() when you need a new set; use update() when you want to modify the existing set.
What does pop() return from a set?
pop() returns an arbitrary element from the set and removes it. Since sets are unordered, you cannot predict which element will be returned.
Can I use add() to add multiple elements?
add() adds only a single element. Use update() to add multiple elements from an iterable.
What is the difference between intersection() and intersection_update()?
intersection() returns a new set containing only common elements. intersection_update() modifies the original set in place, keeping only elements that are present in both sets.
Can I add a list to a set?
my_set.add((1, 2, 3)).
Where to Go From Here
Now that you've mastered set methods, here are the next topics to explore:
Iterate Sets
Learn different ways to loop through sets.
Learn More →Set Comprehension
Learn the powerful set comprehension technique.
Learn More →List vs Set
Understand when to use lists and when to use sets.
Learn More →