list index out of range Python

Asked

Viewed 1,856 times

0

I have lists with numbers in string format and empty spaces. First I want to take the empty spaces, and then I want to convert to float. But right on the first for error appears:

if (x[i]=='' or y[i]==''): Indexerror: list index out of range

How is that possible if the for goes to Len(x)?

def convert_and_eliminate(x,y):

for i in range(0,len(x)-100):
    if (x[i]==''):
        x.pop(i)
        #y.pop(i)

for i in range(0, len(x) - 1500):
    print x[i]
    #x[i]=float(x[i])
    #y[i]=float(y[i])
for i in range (0,1500):
    x.pop()
    y.pop()
  • Give an example (minimum possible) of what you could have x and in y, 'Cause the range goes up len(x)-100?

2 answers

1

When you are in the list.pop(element), you decrease the list size by 1. So if you had a list of size 10, for example, and you pop it, the list becomes size 9. And when you try to index the tenth element, it gives index out of range. I suggest you store the list size in a length variable, for example. Then loop

while i < length:
    if lista[i] == "":
         x.pop(i)
         lenght = length - 1
    i = i + 1

I tried to do the correct identation, but I’m on my cell phone. I hope you can understand. Some considerations:

  • Vc can replace range(0,Len(x)-100) by range(Len(x)-100).

  • I didn’t understand the reason to go up to Len(x) - 100.

  • It is not a good practice to use hardcoded numbers like this 100 and this 1500.

  • Thank you very much! That was exactly the problem!

  • You’re welcome. Give it a OK so people can see that it’s solved. XD

0

I believe the error is in the second part of the validation (y[i]==''); the for goes up to the maximum size of the x, as you said, but if the y is minor, you will receive this error.

If you really need these conditions, change the code:

if (x[i]=='' or (len(y) <= i and y[i]=='')):
  • This is not the case , I even took this parameter to test, I will post the whole code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.