简体   繁体   中英

List index out of range,python troubleshooting

for i in range(0,len(text_list)):
    if (text_list[i] == "!" and text_list[i+1].isupper()):
        print "something"
    else:
        text_list.pop(i)

Traceback (most recent call last):

  File "test.py", line 12, in <module>
    if (text_list[i]=="!" and text_list[i+1].isupper()):

Error:

IndexError: list index out of range

I want to remove all the exclamation marks from a text file that are not at the end of a sentence.

When your i will become last index of the text_list then "text_list[i+1].isupper()" will give you error because i+1 will be out of index range. You can do something like this :

for i in range(0,len(text_list)):
    if(i!=len(text_list-1)):
        if (text_list[i]=="!" and text_list[i+1].isupper()):                
            print "something"   
        else:
            text_list.pop(i)

When i becomes len(text_list) - 1 , i + i is out of bounds. This is your first problem. The second problem is that you are popping within the for loop. This changes the size of the list.

I suggest to save the indices to be removed in a separate list, and then pop them after the loop is finished.

to_remove = []

for i in range(0,len(text_list) - 1):
    if (text_list[i]=="!" and text_list[i+1].isupper()):                
        print "something"   
    else:
        to_remove.append(i)

for i in reversed(to_remove):
    text_list.pop(i) # use del if you don't need the popped value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM