to get right down to it, I'm trying to iterate through a list of coordinate pairs in python and delete all cases where one of the coordinates is negative. For example:
in the array:
map = [[-1, 2], [5, -3], [2, 3], [1, -1], [7, 1]]
I want to remove all the pairs in which either coordinate is < 0, leaving:
map = [[2, 3], [7, 1]]
My problem is that python lists cannot have any gaps, so if I loop like this:
i = 0
for pair in map:
for coord in pair:
if coord < 0:
del map[i]
i += 1
All the indices shift when the element is deleted, messing up the iteration and causing all sorts of problems. I've tried storing the indices of the bad elements in another list and then looping through and deleting those elements, but I have the same problem: once one is gone, the whole list shifts and indices are no longer accurate.
Is there something I'm missing?
Thanks.
Personally, I prefer in-place modification:
->
If the list is small enough, it's more efficient to make a copy containing just the elements you need, as detailed in the other answers.
However, if the list is too large, or for some other reason you need to remove the elements from the list object in place, I've found the following little helper function quite useful:
In your example, this could be applied as follows:
(This is just a list-oriented version of filter_in_place, one which supports all base Python datatypes is a bit more complex).
You probably want
del pair
instead.If you wish to do this in place, without creating a new list, simply use a for loop with index running from len(map)-1 down to 0.
Not very Pythonic, I admit.
If you do not have any other references to the
map
list, a list comprehension works best:If you do have other references and need to actually remove elements from the list referenced by
map
, you have to iterate over a copy ofmap
:itertools.ifilter()/ifilterfalse()
exist to do exactly this: filter an iterable by a predicate (not in-place, obviously). Better still, avoid creating and allocating the entire filtered list object if at all possible, just iterate over it: