0

I am trying to iterate the list and delete the last element based on the condition. But I am getting errors.

x = [0,2,1]
for y, v in enumerate(x):
  if v is 1:  
    del x[y]

print(x)

output:

[0,2,1]

1 Answers1

1

It's not recommended to iterate into a list changing its elements, since you are removing the element by value you can do like this:

x = [0, 2, 1]
for i in range(x.count(1)):
    x.remove(1)

print(x)

Output

[0, 2]
Jhones
  • 19
  • 3
  • this is a pretty inefficient approach though, funamentally polynomial time, you can do it in linear time trivially – juanpa.arrivillaga Sep 01 '22 at 16:45
  • i don't think time efficiency is a variable in this question btw, but nice point – Jhones Sep 01 '22 at 16:47
  • 1
    sure, but you should avoid writing inefficient code when there is an idiomatic, trivial, efficient alternative. e.g. `x = [item for item in x if item != 0]` – juanpa.arrivillaga Sep 01 '22 at 16:48
  • when the code efficiency isn't a deal, since the OP is a beginner clearly, list comprehension isn't the best approach – Jhones Sep 01 '22 at 16:51
  • You can just write the equivalent for-loop, which is perfectly pythonic and idiomatic. Absolutely, a beginner should not be shown unidiomatic, unnecessarily inefficient approaches, especially not if you don't point that out. – juanpa.arrivillaga Sep 01 '22 at 16:52