Home > Enterprise >  IndexError out of range in Python
IndexError out of range in Python

Time:11-25

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

CodePudding user response:

Lenght should <.

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

print(remove_dots("maj.d"))

Gives #

majd

Code correction

You are over complicating solution. This can achieved easily with.

string = "maj.d"
string = string.replace(".", '')
print(string)

Also Gives #

majd

CodePudding user response:

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

CodePudding user response:

You should use replace instead:

string = string.replace(".", "")

CodePudding user response:

In the second for-to-next loop for i in range(len(lst))) change it to for i in range((len(lst))-1) Its because your lst list index count is being exceeded due to that try using -1 in the second for next loop.

CodePudding user response:

Calling lst.remove('.') will remove all elements with value '.', so length of list will change. If you want to remove all dots use str.replace function and replace dot with empty string:

string.replace('.', '')
  • Related