0

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

2 Answers2

2

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
User_Targaryen
  • 4,125
  • 4
  • 30
  • 51
0

You can filter using a list comprehension:

>>> coords =  [(1, 2), (5, 6), (-1, -2), (1, -2)]
>>> [coord for coord in coords
...  if not any(number < 0 for number in coord)]
[(1, 2), (5, 6)]
Peter Wood
  • 23,859
  • 5
  • 60
  • 99