0

When typing the title of my question, Stack Overflow provided a link to this question whose title does admittedly match my question almost exactly:

Calling `.remove()` inside `for` loop doesn't remove all elements

However, that question is about jQuery, which I'd never even heard of before, and the sample code seems to be a lot more complicated than mine. Furthermore, the accepted answer to that question seems to be saying that the code sweeps through the list multiple times and crashes the last time; I don't think that's the case for my example.

def f(x):
    for num in x:
        if num==np.NINF:
            x.remove(num)
    return x
print(f([0,np.NINF,np.NINF]))

This returns [0, -inf] instead of the expected [0]. Why?

J.D.
  • 139
  • 4
  • 14
  • Possible duplicate of https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating, and others https://stackoverflow.com/questions/50127618/modifying-a-list-while-iterating-over-it-with-python – Cireo Jul 03 '20 at 03:56
  • 2
    Trying to modify the same sequence you're iterating over is going to result in tears, no matter which language you try it in. – Mark Ransom Jul 03 '20 at 03:56
  • In general modifying a list while iterating over it is a no-no in python (as well as other languages, you noticed javascript yourself). You can deal with this in a variety of ways (traversing the list in reverse, using an empty slice `[:]` or `list` to fix the original list, collecting indexes, creating a new list without the undesired elements, ...) – Cireo Jul 03 '20 at 03:58
  • Try using `for num in x[:]:`, this will make the copy of original list. – anuragal Jul 03 '20 at 03:58

1 Answers1

0

Don't ever, I repeat ever and ever, use the remove function of a mutable object in a for loop as you are using. What happens if you use it? Let me demonstrate.

Just say I want to remove all values in a list using the same method as you.

x=[1,2,3,4,5,6,7,8]

for i in x:
    x.remove(i)

print(x)

What do you think will be the output?

As expected it should be an empty list, right?

No!

The above program prints the following output.

[2, 4, 6, 8]

Why is this so?

You are calling elements of a mutable object and removing them at the same time, which resets the entire object and its elements.

Now, I think you can understand why your program returns wrong output.

You can achieve the required output in many ways. I will give you one way.

import numpy as np 

def f(x):
    output=[]
    for num in x:
        if num!=np.NINF:
            output.append(num)
    return output

print(f([0,np.NINF,np.NINF]))

Output of the above function is as required.

[0]

This should work for you.

tripleee
  • 175,061
  • 34
  • 275
  • 318
McLovin
  • 555
  • 8
  • 20
  • This is a competent attempt at answering this common FAQ, but you should recognize that this gets asked multiple times per week, if not per day, and concentrate on reviewing the existing answers to the canonical (which this question is now marked as a duplicate of). Also, recommending a beginner to install the huge third-party library NumPy just because it happens to provide a convenient workaround is highly dubious. – tripleee Jul 03 '20 at 18:06
  • @tripleee can you take a look into his program again? He is clearly using numpy and he must have installed it already! – McLovin Jul 04 '20 at 01:58