When doing the loop, there is a range problem and I can't identify it:
def eliminar_elementos(x):
Control=len(x)
y=int(input("Ingrese elemento a eliminar:"))
for j in range(Control):
if x[j]==y:
remover=x[j]
x.remove(remover)
It gives me a range error since when removing an element, the list shrinks. How should I fix it? Reducing the range?
If you want to remove the duplicates "in place", without creating a new list, following your original idea, the key is to iterate the list in reverse order so that the remaining indexes will be valid at all times since we always remove elements after them :
The key is in
range(len(x) - 1, -1, -1)
. The first argument (start
) will be the last index of the list, which is equal to the number of elements in the list minus one (indexed base 0). The second is-1
, since the last index to generate is 0 (the first element of the list), we must remember thatrange
it does not include the valuestop
in the range, so it cannot be 0 or it would only iterate up to 1. The third (step
) logically must also be -1 since the range is generated fromlen(x) - 1
to 0 by subtracting 1 at each step.del
allows you to remove an element from the list using its index,list.remove
it removes the first occurrence of the element passed as an argument, it can be used for this purpose but using awhile
, however it is more inefficient as it needs to iterate repeatedly over the list.You can filter using list comprehension :