-1

.Remove isn't working correctly!

I'm making an Ai and i am trying to remove any words that are the Ai's name or a greeting! But it only removes the first it finds if even that, If someone knows what's going on i'd really appreciate some help. Oh and what_person_said_l_wt is user input tokenized in lowercase (using .lower), just so you know, Thanks here's my code:

Static_Greetings = ["hey","hi","hello"]
Name = ["jarvis"]


for word in what_person_said_l_wt:
      if word in Static_Greetings or word in Name:
            print (word)
            what_person_said_l_wt.remove(word)

Results

input: hey jarvis what is the weather?


Modified: jarvis what is the weather

It does not remove both "Hey" and "Jarvis" to leave just the question: "what is the weather?" as it is supposed to!

Community
  • 1
  • 1
Sergei Glimis
  • 390
  • 2
  • 5
  • 17
  • 1
    Did you *tokenize* the user input, i.e. split it into words? Show that code! – alexis Jul 23 '17 at 01:56
  • 5
    "The standard library isn't working correctly" is almost always wrong for a mature language. It's usually that you have incorrect expectations about how it should work. And in Python particularly, how it works is usually more sensible than your expectations in the long run. Also, your question does not provide a [mcve]. It clearly has errors like the missing initialization of `what_person_said_l_wt`. (You mention that it's user input, but this obviously has nothing to do with your problem and you *should* be able to demonstrate it with a hard coded value.) – jpmc26 Jul 23 '17 at 01:56

2 Answers2

3

You are iterating through a list as you are removing elements from it.

Make a copy of the list, and iterate through that. This way, you can still remove from the original list, while retaining your position in the loop.

Software2
  • 2,358
  • 1
  • 18
  • 28
0

Cannot modify list as you iterate through. Rather, use something like this. It will remove (filter out) the words in static greetings and name.

Static_Greetings = ["hey","hi","hello"]
Name = ["jarvis"]

what_person_said = 'hey jarvis what is the weather?'
print(' '.join([word for word in what_person_said.split()
    if word not in Static_Greetings + Name]))

what is the weather?