-1

Running into something which seems strange. I use a set of lists to hold some data and if a condition is met in them I want to remove that data from each list.

This is what I have currently. It works and removes everything from the first result but when there's more than one meeting the criteria it leaves them.

agecounter = 0
for matches in List1:
  if Condition Met:
    List1.pop(agecounter)
    List2.pop(agecounter)
    List3.pop(agecounter)
  agecounter = agecounter + 1

If I have 10 items in those lists and three meet the criteria it'll remove the first one. I can even print the data from the other results meeting the condition. It prints it to the console just fine, doesn't throw an exception but seems to just ignore the pop.

I might be missing something really obvious here but there's no reason for that not to work, is there?

PoweredByCoffee
  • 1,153
  • 3
  • 14
  • 25
  • 1
    Please give a [mcve] - that *"example"* doesn't help at all. – jonrsharpe Feb 09 '16 at 20:18
  • 1
    Can you provide some code that reproduces your problem? – C_Z_ Feb 09 '16 at 20:18
  • 1
    It's hard to give specific advice without a full [mcve], but in general it's a bad idea to add/remove items from a list at the same time as you're iterating over it. – Kevin Feb 09 '16 at 20:18
  • When you remove one elt the index of following elements change – innoSPG Feb 09 '16 at 20:18
  • Possible duplicate of [Remove items from a list while iterating in Python](http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) – khelwood Feb 09 '16 at 20:32

3 Answers3

3

Traverse your list in reverse order

agecounter = len(List1)-1
for matches in reversed(List1):
    if Condition Met:
        List1.pop(agecounter)
        List2.pop(agecounter)
        List3.pop(agecounter)
    agecounter = agecounter - 1
innoSPG
  • 4,588
  • 1
  • 29
  • 42
2

It's not a good idea to remove elements from a list while iterating over it. You should probably iterate over a copy of your list instead

StephenTG
  • 2,579
  • 6
  • 26
  • 36
2

A full example that shows the problem would help get better answers.

That being said, pop is probably not working as you expect. It's not removing agecounter from the list. It's removing the item at position agecounter.

>>> a = [1,2,3, 4]
>>> a.pop(1)
2
>>> a
[1, 3, 4]
>>> a.pop(2)
4

And when you get higher you're more likely to go off the end, throwing an exception.

>>> a.pop(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range

Adding to @StephenTG's answer you probably want to copy the data rather than modify it during iteration. You can "filter" it using a list comprehension:

a = [1,2,3,4]
>>> b = [2,3]
>>> [x for x in a if x not in b]
[1, 4]
Paul Rubel
  • 26,632
  • 7
  • 60
  • 80