Reputation: 35
Q: Take inputs from user to make a list. Again take one input from user and search it in the list and delete that element, if found. Iterate over list using for loop.
My Answer:
enter = list()
for user_input in range(1, 6):
enter.append(input("Enter a name: "))
new_input = (input("Enter the name you need to find in the list: "))
for check_input in enter:
if check_input == new_input:
enter.remove(new_input)
else:
print("Item not found within the list")
break
print(enter)
However, when I run the code and enter 5 random strings and then enter a string that I want to delete from the list, it never meets the 'if' condition and always shows me that the item wasn't found within the list even though I enter the exact same string as entered within the list.
Upvotes: 1
Views: 34
Reputation: 83527
for check_input in enter:
if check_input == new_input:
enter.remove(new_input)
else:
print("Item not found within the list")
break
This loop will only remove an item if you typed in the first item of the list and then halt. Since remove()
already searches through the entire list, you don't need the for
or if
statement at all:
try:
enter.remove(new_input)
except ValueError:
print("Item not found within the list")
Upvotes: 0
Reputation: 311393
After the first name you check, the loop break
s unconditionally, and further names are not checked. You need to break only if you find the item, and print "item not found" only if you've gone over the entire list:
found = False
for check_input in enter:
if check_input == new_input:
enter.remove(new_input)
Found = true
break
if not found:
print("Item not found within the list")
Upvotes: 2