Python Practice › Set Programs › Program 31
Remove a specific element safely
Write a Python program to remove a specific element, reporting whether it was there.
Input
{5, 10, 15}, remove 10 and 99Output
removed 10
99 not in set
{5, 15}Approach
- Check with
in, thenremove().
Solution
s = {5, 10, 15}for x in [10, 99]: if x in s: s.remove(x) print("removed", x) else: print(x, "not in set")print(s)Output
removed 10
99 not in set
{5, 15}Learn the concept
New to this topic? Read the lesson, then come back.