Python: Removing negatives from a list of numbers

user3161743 picture user3161743 · Jan 6, 2014 · Viewed 43.6k times · Source

The question is to remove negatives from numbers.

When remove_negs([1, 2, 3, -3, 6, -1, -3, 1]) is executed, the result is: [1, 2, 3, 6, -3, 1]. The result is suppose to be [1, 2, 3, 6, 3, 1]. what is happening is that if there are two negative numbers in a row (e.g., -1, -3) then the second number will not get removed. def main(): numbers = input("Enter a list of numbers: ") remove_negs(numbers)

def remove_negs(num_list): 
  '''Remove the negative numbers from the list num_list.'''
    for item in num_list: 
        if item < 0: 
           num_list.remove(item) 

    print num_list

main()

Answer

arshajii picture arshajii · Jan 6, 2014

It's generally a bad idea to remove elements from a list while iterating over it (see the link in my comment for an explanation as to why this is so). A better approach would be to use a list comprehension:

num_list = [item for item in num_list if item >= 0]

Notice that the line above creates a new list and assigns num_list to that. You can also do an "in-place" assignment of the form

num_list[:] = ...

which does not create a new list in memory, but instead modifies the memory location already being pointed to by num_list. This difference is explained in more detail here.