[Tutor] dynamic arrays?
Evert Rol
evert.rol at gmail.com
Mon Sep 27 17:36:36 CEST 2010
> One thing I have never much liked about Python is its need for
> specifically sized arrays and lack of a dynamic, array-like data
> structure. For example, the following fails with a "list assignment
> index out of range" error:
>
> a=[]
> i=0
> for l in open("file.txt", "r"):
> a[i]=l
> i+=1
Hmm, what's wrong with append()?
a = []
for l in open("file.txt"):
a.append(l)
Can't answer on the why, ie, why use append instead of a[i].
Then again, if you want that option, use a dictionary (probably bad idea here, but it works):
a = {}
i = 0
for l in open("file.txt"):
a[i] = l
i += 1
Cheers,
Evert
> Is there something in Python I am missing that would let the above
> work? I am hoping that my annoyance at the apparent lack of such a
> thing is unfounded. BTW, I know why the above throws that exception.
> TIA.
More information about the Tutor
mailing list