• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Remove Elements From a Set in Python

Remove Elements From a Set in Python

Author: Aditya Raj
Last Updated: May 5, 2022

We use sets in python to store unique immutable objects. In this article, we will discuss how we can remove elements from a set in python. For this, we will discuss four approaches using different methods.

Table of Contents
  • Remove Elements From a Set Using The pop() Method
  • Remove Elements From a Set Using The remove() Method
  • Remove Elements From a Set Using The discard() Method
  • Using The clear() Method
  • Conclusion

Remove Elements From a Set Using The pop() Method

We can use the pop() method to remove elements from a set. The pop() method, when invoked on a set, accepts no input argument. After execution, it removes a random element from the set and returns the element. You can observe this in the following example.

mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
element = mySet.pop()
print("The output set is:", mySet)
print("The popped element is:", element)

Output:

The input set is: {1, 2, 3, 4, 5, 6}
The output set is: {2, 3, 4, 5, 6}
The popped element is: 1

The pop() method works well only on sets that are not empty. If we invoke the pop() method on an empty set, it will raise the KeyError exception as shown below.

mySet = set()
print("The input set is:", mySet)
element = mySet.pop()
print("The output set is:", mySet)
print("The popped element is:", element)

Output:

The input set is: set()
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module>
    element = mySet.pop()
KeyError: 'pop from an empty set'

The pop() method removes a random element from the set. If we have to remove a specific element, we can use the approaches discussed below.

Remove Elements From a Set Using The remove() Method

To remove a specified element from a set, we can use the remove() method. The remove() method, when invoked on a set, takes an element as an input argument and removes the element from the set as shown below.  

mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
mySet.remove(3)
print("The output set is:", mySet)

Output:

The input set is: {1, 2, 3, 4, 5, 6}
The output set is: {1, 2, 4, 5, 6}

If the element passed as the input to the remove() method isn’t present in the set, the program will run into a KeyError exception as shown below.

mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
mySet.remove(7)
print("The output set is:", mySet)

Output:

The input set is: {1, 2, 3, 4, 5, 6}
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module>
    mySet.remove(7)
KeyError: 7

Similarly, if we try to remove an element from an empty set using the remove() method, it will raise the KeyError exception.

mySet = set()
print("The input set is:", mySet)
mySet.remove(7)
print("The output set is:", mySet)

Output:

The input set is: set()
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module>
    mySet.remove(7)
KeyError: 7

Remove Elements From a Set Using The discard() Method

When we try to remove an element from a set using the remove() method, and the element is not present in the set, the program will run into a KeyError exception. You can avoid this using the discard() method instead of the remove() method. The discard() method, when invoked on a set, accepts an element as the input argument and removes the element from the set as in the case of the remove() method.

mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
mySet.discard(3)
print("The output set is:", mySet)

Output:

The input set is: {1, 2, 3, 4, 5, 6}
The output set is: {1, 2, 4, 5, 6}

However, the discard() method does not raise an exception if we try to remove an element that isn’t already present in the set. The set remains unchanged and the program doesn’t run into the KeyError exception.

mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
mySet.discard(7)
print("The output set is:", mySet)

Output:

The input set is: {1, 2, 3, 4, 5, 6}
The output set is: {1, 2, 3, 4, 5, 6}

Using The clear() Method

The clear() method is used to remove all the elements from any given set at once. When invoked on a set, the clear() method takes no input arguments and removes all the elements from the set. You can observe this in the following example.

mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
mySet.clear()
print("The output set is:", mySet)

Output:

The input set is: {1, 2, 3, 4, 5, 6}
The output set is: set()

Conclusion

In this article, we have discussed four ways to remove elements from a set in python. To know more about sets, you can read this article on set comprehension in Python. You might also like this article on list comprehension in Python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us