0

I'm very new to python so this might well be a silly question. I am trying to remove all negative values and 0 from a list of integers:

def solution(A):
    for i in A:
        print(i)
        if i <= 0:
            A.remove(i)
    return set(A)

A = [-3,-1,0,-1,3,4,0,10,3,7,8,-10,-9,-78]

I've tested shorter list like [-3,-2,0,1,2,3] to long lists like the one above. However, when I run the code, there is always at least one negative value left in the list A. This particular code outputs:

{-9, -1, 3, 4, 7, 8, 10}

I can't see why it doesn't remove all the negative values. Could someone guide me in the right direction?

1 Answers1

0

Classic mutation during iteration.

>>> A = [-3,-1,0,-1,3,4,0,10,3,7,8,-10,-9,-78]
>>> [a for a in A if a > 0]
[3, 4, 10, 3, 7, 8]

Does this do you what you're looking for?

Pedro Rodrigues
  • 2,520
  • 2
  • 27
  • 26