w3resource

Python: Remove an item from a set if it is present in the set

Python sets: Exercise-5 with Solution

Write a Python program to remove an item from a set if it is present in the set.

Visual Presentation:

NumPy Sets: Remove an item from a set if it is present in the set.

Sample Solution:

Python Code:

# Create a new set 'num_set' with the elements 0, 1, 2, 3, 4, and 5 using a list:
num_set = set([0, 1, 2, 3, 4, 5])

# Print a message to indicate the original set elements:
print("Original set elements:")

# Print the contents of the 'num_set':
print(num_set)

# Print a message to indicate the removal of 0 from the set:
print("\nRemove 0 from the said set:")

# Remove the element 4 from the 'num_set' using the 'discard' method:
num_set.discard(4)

# Print the updated 'num_set' after removing 4:
print(num_set)

# Print a message to indicate the removal of 5 from the set:
print("\nRemove 5 from the said set:")

# Remove the element 5 from the 'num_set' using the 'discard' method:
num_set.discard(5)

# Print the updated 'num_set' after removing 5:
print(num_set)

# Print a message to indicate the removal of 2 from the set:
print("\nRemove 2 from the said set:")

# Remove the element 5 from the 'num_set' using the 'discard' method (note: this should remove 2, not 5):
num_set.discard(5)

# Print the updated 'num_set' after removing 5 (actually removing 2):
print(num_set)

# Print a message to indicate the removal of 7 from the set:
print("\nRemove 7 from the said set:")

# Remove the element 15 from the 'num_set' using the 'discard' method (note: this should not affect the set as 15 is not in it):
num_set.discard(15)

# Print the 'num_set' without any changes, as 15 was not present in the set:
print(num_set)  

Sample Output:

Original set elements:
{0, 1, 2, 3, 4, 5}

Remove 0 from the said set:
{0, 1, 2, 3, 5}

Remove 5 from the said set:
{0, 1, 2, 3}

Remove 2 from the said set:
{0, 1, 2, 3}

Remove 7 from the said set:
{0, 1, 2, 3}

Python Code Editor:

Previous: Write a Python program to remove item(s) from a given set.
Next: Write a Python program to create an intersection of sets.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/sets/python-sets-exercise-5.php