w3resource

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


5. Remove an Item from a Set if Present

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}

For more Practice: Solve these Related Problems:

  • Write a Python program to check if an element exists in a set before removing it using the discard() method.
  • Write a Python program to conditionally remove an element from a set only if it is found, otherwise print a message.
  • Write a Python program to implement a function that safely removes a specified item from a set and returns the modified set.
  • Write a Python program to use an if-statement to remove an element from a set, ensuring that no error is raised if the element is absent.

Go to:


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

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.