Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(".", "").

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading