0
vec = [-4,-2,0,2,4]

for x in vec:
    if x<0:
        print(x)
        vec.remove(x)

print(vec)

This is a program to remove negative numbers and retain positive numbers in a list Without the .remove(x), i printed out -4,-2 But with .remove(x),Why when I print(x), it prints out only -4, and only -4 is removed? Isn't supposedly -2 will also be printed and removed? Isn't supposedly the vec list finally retains 0,2,4 ?

I have tried putting if x <0 or x==-2 , it doesn't work either instead returning me the same problems

I know I can build a new list like vectwo = [x for x in vec if x>0 or x=0] but I just can't figured out the logical fallacy in the iteration I built to remove negative numbers.

Wog12222
  • 35
  • 1
  • 7
  • Don't remove from a list while iterating. It can mess with the iterator and cause weird iterating behavior. – Carcigenicate Mar 12 '21 at 15:19
  • Does it mean remove() function is not suitable for iterator and loops? I should changed it to others like declaring a new list such as vectwo? – Wog12222 Mar 12 '21 at 15:19
  • It's generally a bad idea to change the structure of a data structure while iterating it, unless the iterator explicitly provides a method to do it (like Java iterators do). Yes, creating a new modified list while iterating is the safe way to do it. – Carcigenicate Mar 12 '21 at 15:21
  • Thank you for solving my confusion. – Wog12222 Mar 12 '21 at 15:23
  • Sorry, [this](https://stackoverflow.com/questions/742371/why-does-python-skip-elements-when-i-modify-a-list-while-iterating-over-it) would have been a better dupe. – Carcigenicate Mar 12 '21 at 15:23

1 Answers1

1

Dont remove from the list while iterating. It's cleaner to use another list.

vec = [-4,-2,0,2,4]
vec_copy = []

for x in vec:
    if x >= 0:
        vec_copy.append(x)

print(vec_copy)

You can do this in a single line. But note that you aren't actually removing from numbers from the list, instead you pick the positive items and replace the old list with the new one. It does what you want and it's cleaner this way.

vec = [x for x in vec if x >= 0]
Alex Metsai
  • 1,837
  • 5
  • 12
  • 24
  • `vec = [x for x in vec if x >= 0]` -> OP already knows how to do this... – Justin Mar 12 '21 at 15:28
  • Yes, my mistake for not noticing this. Should I delete this part or the whole post? I just wanted to suggest not to iterate on the list while removing items too. – Alex Metsai Mar 12 '21 at 15:30
  • 1
    No, it's fine.. just an FYI :) – Justin Mar 12 '21 at 15:34
  • 1
    don't delete it ... haha i just want to see whether i have any logical fallacy sure there are better things to use, but when making mistakes, i think i should know what happen , thanks for your feedback mate ! – Wog12222 Mar 12 '21 at 15:36
  • 1
    Okie, thanks for the info Justin. Wong Zi Ao you 're welcome ^__^ – Alex Metsai Mar 12 '21 at 15:37