Click here to Skip to main content
15,905,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Python
#Write a Python program to remove an item from a set if it is present in the set.
set1=set()
num = int(input("How many numbers: "))
for n in range(num):
    numbers = int(input("Enter number "))
    set1.add(numbers)
print("elements in given list is :", set1)
remove1 =input("\n Enter the element you want to remove :")
if remove1 in set1:
    set1.remove(remove1)
    print("The updated set :", set1)
else:
    print("\n The element you have mentioned cannot be found. Please check\n")
    print(set1)


What I have tried:

I have tired with discard and pop () method but the if condition is not getting executed only else part executing.
Posted
Updated 31-Dec-21 3:15am
v3

When you input the numbers you cast them to integer, however you don't do the same when asking for number to delete. So instead of
Python
remove1 =input("\n Enter the element you want to remove :")

try
Python
remove1 =int(input("\n Enter the element you want to remove :"))
 
Share this answer
 
Which means very simply that the condition is failing: remove1 is not in set1. Why not? Because input always returns a string, an d you are comparing a string with an integer.
Either convert all your inputs to integers:
Python
remove1 = int(input("\n Enter the element you want to remove :"))
if remove1 in set1:
    ...
Or none of them:
Python
for n in range(num):
    numbers = input("Enter number ")
    set1.add(numbers)
print("elements in given list is :", set1)
remove1 = input("\n Enter the element you want to remove :")
if remove1 in set1:
    ...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900