Python Practice › Set Programs › Program 31

Remove a specific element safely

EasySet Programs · 31 of 48

Write a Python program to remove a specific element, reporting whether it was there.

Advertisement
Input
{5, 10, 15}, remove 10 and 99
Output
removed 10
99 not in set
{5, 15}

Approach

  1. Check with in, then remove().

Solution

Python
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}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More set programs

← All 48 Set Programs