Conditional Removal from a Set

Tags: removal, Set

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

Example 1:

Input: {1, 2, 3, 4, 5}, 3 
Output: {1, 2, 4, 5}

Example 2:

Input: {5, 7, 8, 9, 10}, 11 
Output: {5, 7, 8, 9, 10}

Use the discard() function which removes an element if it is present, and does nothing otherwise.

def conditional_remove(s, el):
    s.discard(el)
    return s

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!