Search code examples
pythonlistindexoutofboundsexception

IndexError: list index out of range in python for strings


I wanted to remove the word "hello" from this array, but I get the "index out of bounds" error. I checked the range of len(token); it was (0,5).

Here is the code:

token=['hi','hello','how','are','you']

stop='hello'

for i in range(len(token)):
    if(token[i]==stop):
        del(token[i])

Solution

  • You're getting an index out of bounds exception because you are deleting an item from an array you're iterating over.

    After you delete that item, len(token) is 4, but your for loop is iterating 5 times (5 being returned from the initial len(token)).

    There are two ways to solve this. The better way would be to simply call

    token.remove(stop)
    

    This way won't require iterating over the list, and will automatically remove the first item in the array with the value of stop.

    From the documentation:

    list.remove(x): Remove the first item from the list whose value is x. It is an error if there is no such item.

    Given this information, you may want to check if the list contains the target element first to avoid throwing a ValueError:

    if stop in token:
        token.remove(stop)
    

    If the element can exist multiple times in the list, utilizing a while loop will remove all instances of it:

    while stop in token:
        token.remove(stop)
    

    If you need to iterate over the array for some reason, the other way would be to add a break after del(token[i]), like this:

    for i in range(len(token)):
        if(token[i]==stop):
            del(token[i])
            break