-1

Don't understand why 'o' is not deleted

plist = ['D', 'o', 'n', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c', '!']

for i in plist:
    if i in "Don":
        plist.remove(i)

print(plist) -> ['o', "'", 't', ' ', 'p', 'a', 'i', 'c', '!']

PilgrimQA
  • 1
  • 1
  • This is because you are modifying the list while you iterate with it. During the first iteration, `i` points to the first element. For the second iteration, `i` is pointing to the second element, which is now `"n"`, because you deleted the "D". When you need to do something like this, always build a NEW list with the things you want to keep. – Tim Roberts Dec 05 '22 at 00:14
  • Easiest way to do this is `plist = [i for i in plist if i not in "Don"]`. – Samwise Dec 05 '22 at 00:26

1 Answers1

-1

Whe you remove D from the list, o wil move to pos 0.

Just loop over a copy of the list

plist = ['D', 'o', 'n', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c', '!']

for i in plist[:]:
    if i in "Don":
        plist.remove(i)

print(plist)  # Output: ["'", 't', ' ', 'p', 'a', 'i', 'c', '!']

chipchap31
  • 71
  • 8