0

I just want to remove the duplicates of the word passed but it's not working.

wordlist = ["a", "a", 'b', "b", "b", "c", "d", "e"]
new_list = wordlist
word = "a"

for i in range(len(wordlist)):
    if wordlist[i] == word:
        new_list.remove(word)

print(new_list)
Skri11
  • 5
  • 3

3 Answers3

1

Because new_list and wordlist point to the same object. You should use new_list = wordlist.copy() to create the copy of the list.

wordlist = ["a", "a", 'b', "b", "b", "c", "d", "e"]
new_list = wordlist.copy()
word = "a"

for i in range(len(wordlist)):
    if wordlist[i] == word:
        new_list.remove(word)

print(new_list)

Note: It is not advisable to modify the containers while iterating over the same.

Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
1

This post explained well.

In order to make it work, you have to explicitly ask for a copy.

wordlist = ["a", "a", 'b', "b", "b", "c", "d", "e"]
new_list = list(wordlist)

word = "a"

for i in range(len(wordlist)):
    if wordlist[i] == word:
        new_list.remove(word)

print(new_list)
0

Either make new_list a true shallow copy:

new_list = wordlist[:]

Otherwise, new_list is just another reference to the same list object and your initially created range reaches indeces that no longer exist after a couple of removals.

Or (better) build it from scratch:

new_list = [w for w in word_list if w != word]
user2390182
  • 72,016
  • 6
  • 67
  • 89