1

If I am only removing words from the words_left list, why are they also being removed from the word_list and why is not removing 'maegan' which clearly does not have a 'b'.

word_list = ['susan', 'bill', 'terry', 'brian', 'black', 'ryan', 'maegan']
words_left = word_list

for word in word_list:
    if 'b' not in word:
        words_left.remove(word)
        
print(words_left)
print(word_list)

This returns:

['bill', 'brian', 'black', 'maegan']
['bill', 'brian', 'black', 'maegan']

Not, as I expected, this:

['bill', 'brian', 'black']
['susan', 'bill', 'terry', 'brian', 'black', 'ryan', 'maegan']

I'm clearly misunderstanding how the remove function works on lists or am missing something else that isn't entirely obvious to me.

Any help would be much appreciated.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 1
    What do you think `words_left = word_list` does? (Hint: it *doesn't* make a copy of `word_list`.) – Scott Hunter Feb 22 '22 at 20:07
  • Read: https://docs.python.org/3/library/copy.html?highlight=list%20copy – Luuk Feb 22 '22 at 20:11
  • 1
    As an aside, even if you had properly copied the list, using something like `words_left = word_list.copy()`, then your code would still be buggy, because you *should not `.remove` from a `list` while you iterate over it*. Every time you `.remove` from it, all the indices are shifted, so effectively, you'd *skip* the next iteration. That is why it isn't removing `'maegan'`, because when you removed `'ryan'` it skipped the next item. – juanpa.arrivillaga Feb 22 '22 at 20:42
  • So, for the main question, see the first duplicate target, for the second minor question, see the second duplicate target – juanpa.arrivillaga Feb 22 '22 at 20:42
  • thanks @Luuk. That's what I needed. .copy(). – Brian Duryea Feb 22 '22 at 21:13

0 Answers0