Problem with list assignment

Michael Hudson mwh at python.net
Thu Nov 21 11:10:53 EST 2002


Jesse Lawrence <lawrence_jesse at yahoo.ca> writes:

> I'm using the following function to retrieve the
> headers from my mysql columns.  I want to shed the
> extra info, and just maintain the name of the column. 
> This might be really simple, but I can't seem to
> figure out why the assigment of the headers to the
> list header[] in my for loop isn't working.
> 
> Here's the function:
> 
> def mysqlFieldNames(conn):
>    cursor = conn.cursor()
>    cursor.execute ("DESCRIBE guestbook")
>    row = cursor.fetchall()
>    cursor.close()
>    # here's the problem area:
>    header = []
>    i = 0;
>    for r in row:
>       header[i] = r[0]
>       i = i + 1
>    return header
> 
> Now, when I just do a print r[0] in the for loop, I'm
> getting exactly what I want, it's just that when I try
> to assign it to header, that I get a "list assignment
> index out of range" error.
> 
> Am I overlooking something?

That lists don't grow on demand?

Try changing

   header = []
   i = 0;
   for r in row:
      header[i] = r[0]
      i = i + 1
   return header

to 

   header = []
   for r in row:
      header.append(r[0])
   return header

or even

   return [r[0] for r in row]

Cheers,
M.


-- 
  NUTRIMAT:  That drink was individually tailored to meet your
             personal requirements for nutrition and pleasure.
    ARTHUR:  Ah.  So I'm a masochist on a diet am I?
                    -- The Hitch-Hikers Guide to the Galaxy, Episode 9



More information about the Python-list mailing list