list index out of range Python

0

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

  

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

How is this possible if 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()
    
asked by anonymous 08.09.2017 / 20:00

2 answers

1

When you list the .pop (element) list, you decrease the size of the list by 1. So if you had a list of size 10, for example, and give pop, the list becomes size 9. And when you tries to index the tenth element gives index out of range. I suggest you save the size of the list in a variable length, 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 indentation, but I'm on the phone. I hope you understand. Some considerations:

  • You can replace range (0, len (x) -100) with range (len (x) -100).

  • I do not understand why to go to len (x) - 100.

  • It is not good practice to use hardcoded numbers such as this one 100 and one 1500.

10.09.2017 / 19:52
0

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

If you really need these conditions, change the code:

if (x[i]=='' or (len(y) <= i and y[i]=='')):
    
08.09.2017 / 20:06