I wanted to run a for loop for checking every letter in a string and if wanted
list contained the letter, then I wanted the letter to stay and if wanted
did not contain the letter, then I wanted to remove it.
phrase = "Don't panic"
pList = list(phrase)
print(pList)
wanted = ["o","n","t","a","p"]
for anything in pList:
print("Now checking", anything)
if anything not in wanted:
print("Removed",anything)
pList.remove(anything)
elif anything in wanted:
print("Didn't remove", anything)
print(pList)
The following code returns this output-
['D', 'o', 'n', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c']
Now checking D
Removed D
Now checking n
Didn't remove n
Now checking '
Removed '
Now checking
Removed
Now checking a
Didn't remove a
Now checking n
Didn't remove n
Now checking i
Removed i
['o', 'n', 't', 'p', 'a', 'n', 'c']
The code doesn't remove the last letter (i.e. "c") and letters "o", "t", "p" and "c" didn't display the Now checking
output.
I tried removing and some lines and just ran -
phrase = "Don't panic"
pList = list(phrase)
print(pList)
wanted = ["o","n","t","a","p"]
for anything in pList:
print("Now checking", anything)
This time the output made sense -
Now checking D
Now checking o
Now checking n
Now checking '
Now checking t
Now checking
Now checking p
Now checking a
Now checking n
Now checking i
Now checking c
So why doesn't this happen when the full code is run?