1

I am making a command in python that takes a message and turns it into a list, which then removes the first 5 letters (!calc). Afterwards it checks each item in the list if it is a letter or a space. If it is, then it deletes it from the list.

In other words, if it gets the message "!calc abcdef" I want it to print "[]" (nothing).

Instead I get "['a', 'c', 'e']

message = "!calc abcdef"
if message.startswith("!calc"): #checks if the message starts with !calc
  msg = list(message)
  del msg[0:5] #deletes the !calc part
  for i in msg: #goes through each item [" ", "a", "b", "c", "d", "e", "f"]
    if (i.isalpha()) == True: #checks if the item is a letter
      msg.remove(i) #removes the letter
    elif (i.isspace()) == True: #checks if the item is a space
      msg.remove(i) #removes the space
  print(msg)
Cloud9c
  • 219
  • 5
  • 16

1 Answers1

3

The problem arises because you're deleting items in the list while traversing through it. When you do for i in msg, you might actually skip some elements. Observe this piece of code:

L = [1, 2, 3, 4, 5]
for i in L:
    print(i)
    if i % 2 == 0:
        L.remove(i)

You might expect the print statement to print all five elements 1..5, but actually it prints:

1
2
4

To fix this, you can iterate backwards through the array, or use a list comprehension:

msg = [i for i in msg if i.isalpha() == False or i.isspace() == False]

Of course, your whole code could also be cleaned up to an extent using this syntax:

message = ''.join([i for i in message[:5] if not i.isalpha() and not i.isspace()])
TerryA
  • 58,805
  • 11
  • 114
  • 143