0

this is the input value for logic

participant = ['leo', 'kiki', 'eden']
completion = ['eden', 'kiki']

and this is my source code to find word which is can't matching which In a mutual list

for i in participant:
    for j in completion:
        if i == j:
            participant.remove(i)
            completion.remove(i)

why this source code doesn't run to end of list element 'eden'?

currently result is it.

['leo', 'eden']
YangDongJae
  • 95
  • 1
  • 1
  • 7
  • This is a duplicate of https://stackoverflow.com/questions/51601249/should-i-create-a-copy-when-iterating-over-a-list-using-enumerate-in-python, but I'm not sure if there's a better version of it. – Bill Lynch Sep 18 '20 at 00:49
  • You shouldn't add/remove from a list while iterating over the same list. – Rfroes87 Sep 18 '20 at 00:50

3 Answers3

3

From the python documentation:

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

https://docs.python.org/2/tutorial/controlflow.html#for-statements

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

It is because participant and completion are modified during your loop. Try this code. It makes copy of the lists and not change the original ones but the copied ones.

import copy
participant = ['leo', 'kiki', 'eden']
completion = ['eden', 'kiki']

participant_copy = copy.copy(participant)
completion_copy = copy.copy(completion)
for i in participant:
    for j in completion:
        if i == j:
            participant_copy.remove(i)
            completion_copy.remove(j)
Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11
  • if i want to get a same result as like your code to use only one list (don't use copy list), how can i solve this problem? – YangDongJae Sep 18 '20 at 00:56
0

Another alternative solution is to make use of the slice approach, like this, it will be very similar to what you have but slight difference:

Note: this uses the same iterator to go through the list for checking of common items.

participant = ['leo', 'kiki', 'eden']
completion = ['eden', 'kiki']

for i in participant[:]:
  if i in completion:
    participant.remove(i)
    completion.remove(i)

print(participant)
print(completion)

Output:

 ['leo'] #only one non-similar element left
 [] #completion is empty list now
de_classified
  • 1,927
  • 1
  • 15
  • 19