Remove an Element from a Set in Python

While working on a data-cleaning task, I had to remove duplicate values from a dataset that contained city names across different states in the USA. Since I was using Python, I naturally turned to sets because they automatically handle uniqueness.

I realized that I also needed to remove certain elements from the set, like outdated or invalid city names. That’s when I revisited the different ways Python allows us to remove items from a set.

In this tutorial, I’ll walk you through multiple methods to remove elements from a set in Python. I’ll explain each method step by step, share my firsthand experience, and provide full code examples so you can follow along easily.

Set in Python

A set in Python is an unordered collection of unique elements. Unlike lists or tuples, sets do not allow duplicate values. They are especially useful for tasks like removing duplicates, performing mathematical set operations (union, intersection, difference), and checking membership efficiently.

Here’s a quick example of a set:

cities = {"New York", "Los Angeles", "Chicago", "Houston", "Phoenix"}
print(cities)

Output:

{'Chicago', 'New York', 'Los Angeles', 'Houston', 'Phoenix'}

Notice that the order may not be the same as you entered; the set is unordered.

Different Ways to Remove an Element from a Set in Python

Python provides multiple ways to remove elements from a set. Each method has its use case, and I’ll explain when and why you should use one over the other.

Method 1: Use the remove() Method in Python

The remove() method in Python is the most direct way to delete a specific element from a set.

Here’s how I use it:

cities = {"New York", "Los Angeles", "Chicago", "Houston", "Phoenix"}

# Remove "Chicago" from the set
cities.remove("Chicago")

print(cities)

Output:

{'Houston', 'Los Angeles', 'Phoenix', 'New York'}

You can refer to the screenshot below to see the output.

python set remove

Note: If the element does not exist in the set, Python will raise a KeyError.

For example:

cities = {"New York", "Los Angeles", "Chicago"}
cities.remove("Miami")  # Miami is not in the set

This will throw:

KeyError: 'Miami'

So, only use remove() when you are sure the element exists.

Method 2: Use Python’s discard() Method

When I’m not sure if an element exists in a set, I prefer using Python’s discard(). Unlike remove(), it does not raise an error if the element is missing.

Example:

cities = {"New York", "Los Angeles", "Chicago", "Houston"}

# Try to discard "Miami" which is not in the set
cities.discard("Miami")

print(cities)

Output:

{'Los Angeles', 'Houston', 'New York', 'Chicago'}

You can refer to the screenshot below to see the output.

remove from set python

This is safer when working with large datasets where you cannot guarantee the presence of an element.

Method 3: Use the pop() Method

Sometimes, I need to remove an element from a set without caring which element is removed. In such cases, I use pop().

Since sets are unordered, pop() removes and returns an arbitrary element.

Example:

cities = {"New York", "Los Angeles", "Chicago", "Houston"}

removed_city = cities.pop()

print("Removed:", removed_city)
print("Remaining:", cities)

Output (may vary):

Removed: Chicago
Remaining: {'Houston', 'Los Angeles', 'New York'}

You can refer to the screenshot below to see the output.

set remove python

Because sets don’t maintain order, you cannot predict which element will be removed. I only use this when I just need to reduce the size of the set.

Method 4: Use Set Difference (-= Operator)

When I want to remove multiple elements at once, I find the set difference operation very handy.

Example:

cities = {"New York", "Los Angeles", "Chicago", "Houston", "Phoenix"}

# Remove multiple elements
cities -= {"Chicago", "Houston"}

print(cities)

Output:

{'New York', 'Los Angeles', 'Phoenix'}

This approach is very efficient when working with large datasets where you need to remove a group of unwanted values.

Method 5: Use a Loop with discard()

In real-world scenarios, especially when cleaning data, I often need to remove multiple elements conditionally. In such cases, I combine a loop with discard() in Python.

Example:

cities = {"New York", "Los Angeles", "Chicago", "Houston", "Phoenix", "Dallas"}

# Remove cities that start with 'H'
for city in list(cities):
    if city.startswith("H"):
        cities.discard(city)

print(cities)

Output:

{'New York', 'Los Angeles', 'Phoenix', 'Dallas'}

Here, I converted the set to a list before looping to avoid modifying the set while iterating over it.

Method 6: Use Set Comprehension

Another efficient way I like is using set comprehension to create a new set without the unwanted elements in Python.

Example:

cities = {"New York", "Los Angeles", "Chicago", "Houston", "Phoenix"}

# Create a new set without "Chicago"
cities = {city for city in cities if city != "Chicago"}

print(cities)

Output:

{'New York', 'Los Angeles', 'Houston', 'Phoenix'}

This is clean, readable, and avoids modifying the set in place.

Which Method Should You Use?

  • Use remove() if you are sure the element exists.
  • Use discard() if you are not sure and want to avoid errors.
  • Use pop() when you just need to remove any element.
  • Use set difference (-=) when removing multiple elements at once.
  • Use loops or set comprehension when applying conditions for removal.

Real-Life Example – Clean Up a Dataset

Let’s say I have a dataset of U.S. states where some outdated abbreviations need to be removed.

states = {"CA", "TX", "NY", "FL", "IL", "XX", "YY"}

# Outdated codes
invalid_codes = {"XX", "YY"}

# Remove invalid codes
states -= invalid_codes

print(states)

Output:

{'NY', 'TX', 'CA', 'IL', 'FL'}

This is a real-world use case where sets are extremely useful for data cleaning.

While sets in Python are already powerful because they store unique elements, knowing how to remove items effectively makes them even more useful.

I use discard() most often because it’s safe and doesn’t throw errors. But when performance matters, especially with large datasets, I prefer set difference operations.

Now that you’ve seen multiple methods, you can confidently choose the one that best fits your scenario.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.