Python – Remove Set Items

In this chapter, we will explore Python sets remove with examples in the hopes that we will learn what we need to know.

Python sets remove Syntax:

set.remove(element)

Python sets remove() Parameters:

Remove() removes an element from a set by taking one argument.



Remove Item

Python sets remove an item by using either the remove() method or the discard() method.

Using the remove() method, remove “Finland”:

Example: 

country_set = {"United States of America", "United Kingdom", "Finland", "Australia"} country_set.remove("Finland") print(country_set)

Reminder: The remove() method will raise an error if the item to be removed does not exist.

Using the discard() method, remove “Finland”:

Example: 

country_set = {"United States of America", "United Kingdom", "Finland", "Australia"} country_set.discard("Finland") print(country_set)

Reminder: Discard() method will not raise an error if the item to remove does not exist.

You can also remove an item with the pop() method, but this method will remove the last item.

When removing items from Python sets, remember that sets are unordered, so you don’t know which item gets removed.

A pop() method returns the removed item as its return value.

Using the pop() method, remove the last item:

Example: 

country_set = {"United States of America", "United Kingdom", "Finland", "Australia"} a = country_set.pop() print(a) #extracted item print(country_set) #the set after deletion

Reminder: As sets are unordered, you have no idea which item will be removed when you use the pop() method.

By calling clear(), the set is eliminated:

Example: 

country_set = {"United States of America", "United Kingdom", "Finland", "Australia"} country_set.clear() print(country_set)

Delete the set completely with the del keyword:

Example: 

country_set = {"United States of America", "United Kingdom", "Finland", "Australia"} del country_set print(country_set)

Where to use Python- Set Remove Method ?

When you have a set and want to remove a particular element from it, you can use the remove() method. This method takes the value of the element as an argument and removes the element from the set if it exists. For example, if you have a set {1, 2, 3, 4, 5} and want to remove the element 3, you can use my_set.remove(3), resulting in the set {1, 2, 4, 5}.

Your reaction matters to us. Leave your thoughts below to acknowledge our efforts or provide suggestions for the betterment of this site.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *