(Inadvertently) skip items when repeating a list

I have a list, and I want to remove items from it that do not appear in another list. I tried the following:   

for w in common:
        for i in range(1,n):
            if not w in words[i]:
                common.remove(w)
However, this does not allow you to delete some items. Adding Print Operators
for w in common:
        for i in range(1,n):
                        print w
            if not w in words[i]:
                print w
                common.remove(w)
leads to the fact that some of them are never printed. Any ideas on what's going on? I assume that the answer is simple, and I simply do not have adequate knowledge of Python, but I am completely not up to date.
+3
source share
5 answers

I think you can simplify your statement like this:

filtered = filter(lambda x: x in words, common)

, . , x not in words , , , .

, , , .

filtered = [x for x in common if x in words]

- EDITED. , , . !

+8

, . .

for w in common[:]:
    for i in range(1,n):
        if not w in words[i]:
            common.remove(w)
+3

Python:

, ( , ). , (, ), .

+3
source

You modify the list when you try to iterate through it. You can change the first line of code to iterate over a copy of the list (using common [:]).

+2
source

If you delete (say) paragraph 5, then the old element 6 will now be paragraph 5. So, if you are thinking of going to paragraph 6, you will skip it.

Is it possible to repeat iteration on this list? Then index changes occur in parts that you have already processed.

+1
source

Source: https://habr.com/ru/post/1760329/


All Articles