'Python list.remove() not working as expected. It is removing from multiple lists when I'm clearly specifying only one [duplicate]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
