Why won't the loop go through all the items?

The code is to remove all letters from a string and only leave letters. I am wondering why the loop won’t go through each loop and remove it. It will skip a term and leave letters.

Repl link:

#Entire Alphabet
alphabet = [
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q",
  "r", "s", "t", "u","v","w", "x", "y", "z"]
#Empty list, but will append terms to it and add them up in the end.
number_list = []

#Defining functions
def split(word):
  return list(word)

def converter():
  global message
  global i
  global new_message
  while i < len(message_list):
    print(message_list[i] in alphabet)
    if message_list[i] in alphabet:
      message_list.remove(message_list[i])
      print(message_list)
    i += 1

  new_message = "".join(message_list)
  

def main(): 
  global message_list
  while True:
    message = input("Enter message: ")
    message_list = split(message)
    converter()
    print(new_message)


if __name__ == "__main__":
    main()
1 Like

For example, I would enter “1heel” and get “1el”.

1 Like

I’m confused; do you mean the code is intended to strip characters, excluding those from the alphabet, from a given text?

1 Like

It’s supposed to be heel, correct?

You should not remove from the same list while iterating over it, unless you are only removing a single item.
Consider the following example:

a = [1, 2, 3, 4, 5]
for i in a:
  a.remove(i)
print(a)

This will print [2, 4]. The reason is that, when it removes an item, the items after it have their index decreased by one (to fill in the removed spot), but in the iteration, the index that is used for iteration still goes up by one, it never revisits the same index, so the item that filled the removed item’s spot gets skipped.

An easy solution is to copy the list for iteration (and you should use for loops instead of while loops:

for c in list(message_list):
  print(c.isalpha())
  if c.isalpha():
    message_list.remove(c)
    print(message_list)

Best ways to copy a list:

message_list[:]
tuple(message_list)
list(message_list)
message_list.copy()

There’s also some other improvements to be made, such as using isalpha(), removing global variables, etc.

4 Likes