-1

(I see that this question is a duplicate. Sorry everybody, I wasn't sure of the wording so I couldn't find the other question)

I define the following list of strings:

x=["foo_a","foo_a_b","foo"]

then I do the following:

for i in x:
    if (("a" not in i) or ("b" in i)):
        x.remove(i)

and I get

In [92]: x
Out[92]: ['foo_a', 'foo']

I would expect the element "foo" to be removed too, because it doesn't contain "a" and so it doesn't verify the first condition.

What am I missing?

valerio
  • 677
  • 4
  • 12
  • 25

1 Answers1

0

You are modifying the list you are iterating on. Iterate over a copy of x:

x=["foo_a","foo_a_b","foo"]
for i in list(x):
    if (("a" not in i) or ("b" in i)):
        x.remove(i)

Or even better, avoid using a for loop and create a new list with a list comprehension and assign it to x

x = ["foo_a","foo_a_b","foo"]
x = [item for item in x if not (("a" not in i) or ("b" in i))]
zondo
  • 19,901
  • 8
  • 44
  • 83
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82