IndexError out of range in Python

Hi I am hoping you could help me in this python error that i could not solve

def remove_dots(string):
    lst = []

    for i in range(len(string)):
        lst.append(string[i])

    for i in range(len(lst)):

        if i <= len(lst): 

            if lst[i] == ".":
                lst.remove(lst[i])

            else:
                continue

    nstring = "".join(lst)

    return nstring

The Error:

        if lst[i] == ".":
IndexError: list index out of range

And this is the call of the function:

print(remove_dots("maj.d"))

So if any one can help me and thank you

>Solution :

Replacing i <= len(lst) with i < len(lst) makes your code work, but it doesn’t do what you might think it does. lst.remove('.') removes all dots from the list, so the whole loop is basically superfluous. You aren’t supposed to remove elements from a list while iterating over it because it will change the length and you end up with index errors. You prevented that with the if i < len(lst): condition, but computing the length over and over for every iteration is very inefficient.

What you really want to do is something like this:

def remove_dots(string):
    output = ""
    
    for char in string:
        if char != ".":
            output += char
    
    return output

This is a basic technique that you will use over and over while learning programming. However, if there is a builtin method that does the job, you should use it, so as others pointed out: just do string.replace(".", "").

Leave a Reply