-1

I want to remove an specific element from the list n times, if a put 7 I want to remove all sevens. I'm trying to run this code but get me an error:

elements = [1, 2, 3, 4, 4, 5, 6, 5, 7, 7]
valor = int(input('type a value: '))
for i in range(len(elements)):
    if (elements[i] == valor):
        elements.remove(valor)

print(elements)

IndexError: list index out of range

2 Answers2

1

You can make use of the list comprehension like this:

elements = [1, 2, 3, 4, 4, 5, 6, 5, 7, 7]
valor = int(input('type a value: '))
print([e for e in elements if e != valor])
1218985
  • 7,531
  • 2
  • 25
  • 31
0

You should not remove values during a for each loop. This will work:

elements = [1, 2, 3, 4, 4, 5, 6, 5, 7, 7]
newElements = []
valor = int(input('type a value: '))
for i in elements:
    if (i != valor):
        newElements.append(i)
elements = newElements
print(elements)
Michael Royston
  • 226
  • 1
  • 8