Skip to content

How to Remove Items from Python Sets

How to Remove Items from a Python Set Cover Image

In this tutorial, you’ll learn how to remove items from a Python set. You’ll learn how to remove items using the remove method, the discard method, the pop method, and the difference_update method. You’ll learn the differences between each of these methods and when you may want to use which. You’ll also learn how to remove items from sets conditionally, such as all numbers below a threshold.

The Quick Answer: Use discard to Remove an Item from a Set in Python

# Remove an Item Safely from a Python Set
numbers = {1, 2, 3, 4, 5}
numbers.discard(2)

print(numbers)
# Returns: {1, 3, 4, 5}

A Quick Primer on Python Sets

Sets are a unique container data structure in Python. Sets are created by using comma-separated values between curly braces {}.

Sets have the following main attributes:

  • Unordered: meaning that we can’t access items based on their index
  • Unique: meaning that an item can only exist once
  • Mutable: meaning that the set itself can be changed (while sets must contain immutable items themselves)

Python sets also provide a number of helpful methods, such as being able to calculate differences between sets.

We can create an empty set by using the set() function. Let’s see what this looks like:

# Creating empty sets
set1 = set()

We need to be careful to not simply create an empty set with curly braces. This will return a dictionary instead. In order to create a set using only curly braces, it must contain at least one item.

Remove an Item from a Python Set with remove

Python sets come with a method, remove, that lets us remove an item from a set. The method accepts a single argument: the item we want to remove.

Let’s take a look at how we can use the method:

# Remove an Item from a Python Set using .remove()
numbers = {1, 2, 3, 4, 5}
numbers.remove(2)

print(numbers)
# Returns: {1, 3, 4, 5}

We can see that by passing in the value of 2 that it was successfully removed from our set. The operation took occurred in-place, meaning that we didn’t need to re-assign the set.

Something to note, however, is that if we try to remove an item that doesn’t exist, Python will raise a KeyError. Let’s see what this looks like:

# Raising an Error When an Item Doesn't Exist
numbers = {1, 2, 3, 4, 5}
numbers.remove(6)

# Raises KeyError: 6

In order to prevent the error from ending our program, we need to be able to handle this exception. We can either first check if any item exists in a set, or we can use a try-except statement. Let’s see how this works:

# Preventing a Program from Crashing with set.remove()
numbers = {1, 2, 3, 4, 5}
try:
   numbers.remove(6)
except KeyError:
   pass

Typing try-except statements can be a little tedious. Because of this, we can use the discard method to safely remove an item from a Python set.

Remove an Item Safely from a Python Set with discard

In the above section, you learned about the Python set.remove() method. The set.discard() method accomplishes the same thing – though it handles missing keys without throwing an exception. If an item that doesn’t exist is passed into the method, the method will simply return None.

Let’s see how this works:

# Remove an Item from a Python Set using .discard()
numbers = {1, 2, 3, 4, 5}
numbers.discard(2)
print(numbers)

# Returns: {1, 3, 4, 5}

We can see in the first use of discard that we were able to drop an item successfully.

Now, let’s try using the discard method to remove an item that doesn’t exist:

# Safely handle removing items that don't exist
numbers = {1, 2, 3, 4, 5}
numbers.discard(6)
print(numbers)

# Returns: {1, 3, 2, 4, 5}

We can see here that when we attempted to remove an item that didn’t exist using the set.discard() method, nothing happened.

In the next section, you’ll learn how to use the set.pop() method to remove an item and return it.

Remove and Return a Random Item from a Python Set with pop

The Python set.pop() method removes a random item from a set and returns it. This has many potential applications, such as in game development. Not only does it remove an item, but it also returns it meaning that you can assign it to a variable. For example, in a card game where each item only exists once, this could be used to draw a card.

Let’s see how this method works to delete an item from a set:

# Remove an Item from a Python Set using .pop()
numbers = {1, 2, 3, 4, 5}
number = numbers.pop()

print('number: ', number)
print('numbers: ', numbers)

# Returns:
# number:  1
# numbers:  {2, 3, 4, 5}

We can see that when we pop a value from a set, the value is both returned and removed from the set.

What happens when we try to apply the .pop() method to an empty set? For example, if we had drawn all the cards from our set of cards?

# Popping an empty set
numbers = {1, 2, 3, 4, 5}
for _ in range(6):
    numbers.pop()
    print(numbers)

# Returns:
# {2, 3, 4, 5}
# {3, 4, 5}
# {4, 5}
# {5}
# set()
# KeyError: 'pop from an empty set'

In the code above, we pop an item from a set and print the remaining items six times. After the fifth time, the set is empty. When we attempt to pop an item from an empty set, a KeyError is raised.

In the next section, you’ll learn how to remove multiple items from a Python set.

Remove Multiple Items from a Python Set with difference_update

There may be many times when you don’t simply want to remove a single item from a set, but rather want to remove multiple items. One way to accomplish this is to use a for loop to iterate over a list of items to remove and apply the .discard() method. Let’s see what this might look like:

# Deleting multiple items from a set using a for loop
numbers = {1, 2, 3, 4, 5}
numbers_to_remove = [1, 3, 5]

for number in numbers_to_remove:
    numbers.discard(number)

print(numbers)

# Returns: {2, 4}

While this approach works, there is actually a much simpler way to accomplish this. That is by using the .difference_update() method. The method accepts an iterable, such as a list, and removes all the items from the set.

Let’s convert our for loop approach to using the .difference_update() method:

# Deleting multiple items from a set using .difference_update()
numbers = {1, 2, 3, 4, 5}
numbers_to_remove = [1, 3, 5]

numbers.difference_update(numbers_to_remove)

print(numbers)

# Returns: {2, 4}

We can see that by applying the .difference_update() method, that we were able to easily delete multiple items from a set. What’s even more is that the method does this in a safe manner. If we passed in an item that didn’t exist, the method would not raise an error.

Remove All Items from a Python Set

Python provides an easy method to remove all items from a set as well. This method, .clear(), clears out all the items from a set and returns an empty set.

Let’s see how this method works:

# Delete all items from a Python set
numbers = {1, 2, 3, 4, 5}
numbers.clear()

print(numbers)
# Returns: set()

In the next section, you’ll learn how to delete items from a set based on a condition.

Remove Items from a Python Set Conditionally

In this final section, you’ll learn how to remove items from a set based on a condition. First, you’ll learn how to do this using a for loop and the .discard() method and later with a set comprehension.

Let’s take a set of numbers and delete all items that are even using a for loop:

# Removing items conditionally from a set
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}

for number in list(numbers):
    if number % 2 == 0:
        numbers.discard(number)

print(numbers)
# Returns: {1, 3, 5, 7, 9}

The important thing to note here is that we need to iterate over the items in the set after we convert it to a list. If we don’t do this, we encounter a RuntimeError.

We can also accomplish this using a Python set comprehension. These work very similar to Python list comprehensions and we can use them to easily filter our sets.

# Removing items conditionally from a set
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
numbers = {number for number in numbers if number % 2 != 0}

print(numbers)
# Returns: {1, 3, 5, 7, 9}

We can see that this approach is quite a bit shorter and a lot more readable. It can also be intimidating to newcomers to the language, so use whichever approach is easier for you to be able to understand in the future.

Conclusion

In this tutorial, you learned how to use Python to remove items from a set. You learned how to use the .pop() and .discard() methods. You also learned how to remove multiple items or all items from a set. Finally, you learned how to remove items conditionally from a set.

To learn more about Python sets, check out the official documentation here.

Additional Resources

To learn more about related topics, check out these tutorials here:

Leave a Reply

Your email address will not be published.