1

Trying to remove negative numbers from a list. I kept running into an issue where two successive negative numbers did not get removed. My code is quite simple:

numbers = [-5, 1, -3, -1]

    def remove_neg(num_list):
        for item in num_list:
            if item < 0:
                num_list.remove(item)

    print(remove_neg(numbers))
    #[1, -1]

I found the answer online after trying 4 different versions of my code and pulling a few hairs out of my head. The answer I found assigned r = numbers[:] and then removed items from r instead of the initial list.

    def remove_neg(num_list):
        r = numbers [:]
        for item in num_list:
            if item < 0:
                r.remove(item)
        print(r)

I understand this concept to have two list variables point to separate data. What I don't understand, is why my initial code doesn't work. Shouldn't for i in numbers: iterate through every item in the list? Why would two successive numbers not be treated the same? I've scoured looking for why and can't seem to find an answer.

Mureinik
  • 297,002
  • 52
  • 306
  • 350

1 Answers1

0

In the first example you're modifying the list while iterating over it, which, as you've seen, messes up the iteration. While the second example works, it's very inefficient, and it would be much easier to use a list comprehension to construct a new list without the negatives:

def remove_neg(num_list):
    return [x for x in num_list if x > 0]
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • AH! Your very first sentence clicked the light bulb in my head! Now I get it! Thanks so much for the reply and the list comprehension example. – trimonkeytri Nov 24 '17 at 19:32