Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
IndexError happens in pythonista 3
-
import matplotlib.pyplot as plt;
x = [ ];
y = [ ];readFile = open('xy.txt','r');
for line in readFile:
# file is open with a line in variable 'line'
# do something with this line
print(line);
# split the line based on whitespace
splitUP = line.split();print('x = ',splitUP[0],'and y = ',splitUP[1]); # add x and y to the arrays x.append(splitUP[0]); y.append(splitUP[1]);
When I run it , it shows IndexError: list index out of the range
-
Without seeing the data or the complete stack trace I can only guess what the issue is. But two possibilities come to mind:
line
is a white space character so there is nothing to split which results in 2).splitUP
has a value of['xy']
instead of['x', 'y']
Either way try printing the value ofsplitUP
Without breaking it first. IEprint(splitUP)
and see what that gives.
-
This is my data
2 1.69
3 3.25
4 2.44
5 3.45
6 6.29
7 3.94
8 5.23
9 5.78
10 6.31
11 8.25
12 7.84Stake:
---------------------------below is my program----------------------------
import matplotlib.pyplot as plt;
x = [ ];
y = [ ];readFile = open('xy.txt','r');
for line in readFile:
print(line); splitUP = line.split(); print('x =',splitUP[0],'and y =',splitUP[1]); x.append(splitUP[0]); y.append(splitUP[1]);
readFile.close();
plt.plot(x,y);
plt.show();
-
Stake:
print('x =',splitUP[0],'and y =',splitUP[1]);
IndexError: list index out of range -
you should use try, then catch the IndexError and print both the line, and the split. You may find that you have a blank line at the end of your file, etc.
-
by the way, you might find numpy.loadtxt the best way to read this type of file, especially if you are using this in matplotlub or numpy.
-
I would add the line
print(splitUP, len(splitUP))
before your current print() line and I would remove all those unnecessary semicolons ;-). I think the others are correct. You have a blank line in your input. -
Thank you guys! I do have a blank line in my file but now it's gone!