0
l1=[int(i) for i in input().split(" ")]
itemToRemove=int(input())
for i in l1:
    if i == itemToRemove:
        l1.remove(i)
print(l1)
input: 1 2 2 2 3 4
       2

output:1 2 3 4

but the expected output should be

output:1 3 4

How could I fix this?

KetZoomer
  • 2,701
  • 3
  • 15
  • 43
Mickey
  • 31
  • 2
  • Take a look at this link for the some approches: https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list – KetZoomer Jul 11 '21 at 15:25

2 Answers2

1

You're changing the list while iterating over it. This is never a good idea. A better idea would be to use a while loop that ran whenever the element is in the list. Then, you could remove the element.

Code:

l1=[int(i) for i in input().split(" ")]
itemToRemove=int(input())

while itemToRemove in l1:
    l1.remove(itemToRemove)

print(l1)

If you want to do it with a for loop, iterate over a copy of a list:

l1=[int(i) for i in input().split(" ")]
itemToRemove=int(input())
for i in l1.copy():
    if i == itemToRemove:
        l1.remove(i)
print(l1)

You can also iterate over the number of times the itemToRemove is in l1.

l1=[int(i) for i in input().split(" ")]
itemToRemove=int(input())
for _ in range(l1.count(itemToRemove)):
    l1.remove(itemToRemove)
print(l1)
KetZoomer
  • 2,701
  • 3
  • 15
  • 43
0

The easiest method is to use while loop to compare:

l1=[int(i) for i in input()]
itemToRemove=int(input())
while itemToRemove in l1: l1.remove(itemToRemove)
print (l1)
yogender
  • 496
  • 4
  • 7