Reputation: 795
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
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
Reputation: 137557
Several problems:
'NM'
in the list that has no such item.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