[Tutor] dynamic arrays?

Vince Spicer vince at vinces.ca
Mon Sep 27 17:41:41 CEST 2010


On Mon, Sep 27, 2010 at 9:32 AM, Alex Hall <mehgcap at gmail.com> wrote:

> Hi all,
> 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
>
> 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.
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


Your method works ok for dictionaries but when working with lists
you can append data.

#method 1: works with any iterator
data=[]
for line in open("file.txt", "r"):
    data.append(line)

#method 2: this will convert a file into an array
data = open("file.txt", "r").readlines()

#method 3: if you had to know the line number
a = []
for i, line in enumerate(open('flie.txt')):
    print i, line
    a.append(line)

Hope this helps
-- 
Vince Spicer
Lead Developer - MCE Computing

-- 
Sent from Ubuntu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/3231130f/attachment.html>


More information about the Tutor mailing list