Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
99 views
in Python by (114k points)
How to remove elements from a set in Python?

Please log in or register to answer this question.

1 Answer

0 votes
by (114k points)

You can remove elements from a set in Python using several methods:

Using the remove() method: The remove() method removes a specified element from the set. If the element is not present in the set, then a KeyError is raised.

Example:

my_set = {'apple', 'banana', 'cherry'}
my_set.remove('banana')
print(my_set)  # Output: {'cherry', 'apple'}
 

Using the discard() method: The discard() method removes a specified element from the set. If the element is not present in the set, then nothing happens.

Example:

my_set = {'apple', 'banana', 'cherry'}
my_set.discard('banana')
print(my_set)  # Output: {'cherry', 'apple'}
 

Using the pop() method: The pop() method removes an arbitrary element from the set and returns it. Since sets are unordered, the element that is removed is unpredictable.

Example:

my_set = {'apple', 'banana', 'cherry'}
removed_element = my_set.pop()
print(removed_element)  # Output: 'banana'
print(my_set)  # Output: {'cherry', 'apple'}
 

Using the clear() method: The clear() method removes all the elements from the set, resulting in an empty set.

Example:

my_set = {'apple', 'banana', 'cherry'}
my_set.clear()
print(my_set)  # Output: set()
 

Note that all these methods modify the original set. If you want to create a new set with certain elements removed from the original set, you can use set comprehension or the difference() method.

Related questions

0 votes
1 answer
asked Mar 22, 2023 in Python by kvdevika (114k points)
0 votes
1 answer
asked Mar 22, 2023 in Python by kvdevika (114k points)
0 votes
1 answer
asked Mar 22, 2023 in Python by kvdevika (114k points)
0 votes
1 answer
asked Mar 22, 2023 in Python by kvdevika (114k points)
0 votes
1 answer
asked Mar 22, 2023 in Python by kvdevika (114k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...