Andy_A̷n̷d̷y̷
Andy_A̷n̷d̷y̷

Reputation: 795

Operations with lists

I have the following list:

Words = ['This','is','a','list','and','NM,']

Note: Words[5] >>> NM, (with a comma(,))

New_List = []
for word in Words:
    if word[:2] =="NM":
        Words.insert((Words.index("NM")),input("Input a " + ac_to_word("NM") + ": "))
        Words.remove("NM")

Whenever I try to run this I get:

 Words.insert((Words.index("NM")),input("Input a " + ac_to_word("NM") + ": "))
ValueError: 'NM' is not in list

Yet "NM" is the in index 5. What's going on here? I am asking for word[:2] not the whole word.

I tried figuring out the problem,but no one was around to look at my code, and give me feedback, so I though maybe some people out there might be able to help. If you see a mistake, please show me where. Any help is appreciated!

Upvotes: 3

Views: 134

Answers (2)

roippi
roippi

Reputation: 25974

The error is coming from here:

Words.index("NM")

'NM' is not in your list of strings.

Doing insert and remove operations on a sequence while you iterate over it is a bad, bad idea. It is a surefire way to skip an item, or to double-operate on an item. Also, you should not be doing linear searches with index since a) it is slow and b) what happens if you have duplicates?

Just use enumerate:

for i,word in enumerate(words):
    if word[:2] == 'NM':
        words[i] = input('replace NM with something: ')

Upvotes: 2

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137557

Several problems:

  1. You're trying to access a string 'NM' in the list that has no such item.
  2. You're modifying the list as you iterate over it. Don't do this! It will have unexpected consequences.

An easier way here would probably be to iterate over the list indices instead of the items:

Words = ['This','is','a','list','and','NM,']
for i in xrange(len(Words)):
    if Words[i].startswith('NM'):
        Words[i] = input("Input a " + ac_to_word("NM") + ": ")

Notice that I'm simply replacing the NM... items with the result of input(). This is more efficient than inserting and removing elements.

Upvotes: 2

Related Questions