[Tutor] IndexError and appending to lists [Was: Re: Need Helpon Assignment]

Alan G alan.gauld at freenet.co.uk
Wed Aug 24 09:41:56 CEST 2005

Hi Tom,

Glad you got it working with Danny's help.

I'll throw in some style points too.

> input = open('/home/tom/Python/Input/SPY3.txt', 'r')

> N=0
> s = 'boo'
> while s:
>    s = input.readline()
>    if s == '':break

You might find it easier to use a for loop.

you could for example use

for s in input:

to replace most of the above code and, in the process, 
eliminate the need for N completely, see below...

>    s = s[:-2]
>    T[N] = s.split(',')

Since you are using append elsewhere why not for T too?
And if you store the split result in a local value before 
putting it into T you can use that variable in all the 
following appends to save indexing T...

>    date.append(T[N][0])
>    open.append(float(T[N][1]))
>    hi.append(float(T[N][2]))
>    lo.append(float(T[N][3]))
>    close.append(float(T[N][4]))
>    vol.append(float(T[N][5]))

>    N+=1

And with the for loop you don;t need to increment N either.

> print N
> for i in range(N):

And you can use len(T) to replace N here.

>    T[i]

This doesn't do anything! :-)

>    print T[i]
>    print date[i], open[i], hi[i], lo[i], close[i], vol[i]
> print T[1][2], T[0][0]
> z = (hi[2] +lo[2])/2.0
> print z


Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list