1

Currently, I want to remove a value that is being looped through if it exists in both lists, as such:

for value in Word1:
    if value in Word2:
        Word1.remove(value)
        Word2.remove(value)

However, this code is returning ['a', 'b', 'b'] for the Word1: ['a', 'a', 'a', 'b', 'b', 'b'] and Word2: ['a', 'a', 'b', 'b'] when I would expect it to return ['a', 'b']. What is causing this issue? Pythontutor's visualisation doesn't seem to be helping me.

Sundrah
  • 785
  • 1
  • 8
  • 16
  • You are changing the lengths of the lists while iterating over them - this is a very bad move. Note that using `set` methods would simplify this significantly. – jonrsharpe Apr 12 '15 at 10:59

1 Answers1

0

You must not change a list, while iterating over it. First, determine the elements, to be removed, then remove them:

to_be_removed = set(Word1).intersection(Word2)
Word1 = [w for w in Word1 if w not in to_be_removed]
Word2 = [w for w in Word2 if w not in to_be_removed]
Daniel
  • 42,087
  • 4
  • 55
  • 81