Jack Jack - 1 month ago 9
Python Question

Removing coordinates from list on python

I have created a list full of "coordinates" in Python: L1 = [(1,2), (5,6), (-1,-2), (1,-2), etc..].

If I wanted to remove all items in the list which contained negative numbers, how would I do this?

I've tried:

for (a,b) in L1:
if a < 0 or b < 0:
L1.remove(a,b)


But it isn't working. Would very much appreciate any help.

Jack

Answer

You cannot change something while you're iterating it. The results are weird and counter-intuitive, and nearly never what you want. In fact, many collections explicitly disallow this (e.g. sets and dicts).

Instead, iterate over a copy (for e in a[:]: ...) or, instead of modifying an existing list, filter it to get a new list containing the items you want ([e for e in a if ...]). Note that in many cases, you don't have to iterate again to filter, just merge the filtering with the generation of the data.

L2 = []
for (a,b) in L1:
  if a >= 0 and b >= 0:
    L2.append((a,b))

L1 = L2
print L1