Much simpler:
>>> a = [ 1, 2, 3, -3, 6, -1, -3, 1]
>>> [x for x in a if x >= 0 ]
[1, 2, 3, 6, 1]
If you really do want to loop, try this:
def remove_negs(num_list):
r = num_list[:]
for item in num_list:
if item < 0:
r.remove(item)
print r
This does what you want:
>>> remove_negs([ 1, 2, 3, -3, 6, -1, -3, 1])
[1, 2, 3, 6, 1]
The key is that the assignment statement r = num_list[:]
makes a copy of num_list. In order not to confuse the loop, We then remove items from r
rather than from the list we are looping over.
More: Python's treatment of variables is a bit subtle. Python keeps variable names, like r
or num_list
separate from variable data, such as [1, 2, 3, 6, 1]
. The names are merely pointers to the data. Consider the assignment statement:
r = num_list
After this statement is run, r
and num_list
both point to the same data. If you make a change to r
's data, you are also making a change to num_list
's data because they both point to the same data. Now, consider:
r = num_list[:]
This statement tells python to modify num_list
's data by taking only certain elements of it. Because of this, python makes a copy of num_list
's data. It just so happens that [:]
specifies that we want all of num_list
's data unchanged but that doesn't stop python from making a copy. The copy is assigned to r
. This means that r
and mum_list
now point to different data. We can make changes to r
's data and it doesn't affect num_list
's data because they have different data.
If this is new to you, you might want to look at this tutorial about python's approach to variable names and variable data: Understanding Python variables and Memory Management
Examples:
>>> a = [ 1, 2, 3, -3, 6, -1, -3, 1]
>>> b = a # a and b now point to the same place
>>> b.remove(-1)
>>> a
[1, 2, 3, -3, 6, -3, 1]
Contrast with:
>>> a = [ 1, 2, 3, -3, 6, -1, -3, 1]
>>> b = a[:] # a and b now point to different data
>>> b
[1, 2, 3, -3, 6, -1, -3, 1]
>>> b.remove(-1)
>>> b
[1, 2, 3, -3, 6, -3, 1]
>>> a
[1, 2, 3, -3, 6, -1, -3, 1]