Problem with list assignment

Pedro RODRIGUEZ pedro_rodriguez at club-internet.fr
Thu Nov 21 11:16:46 EST 2002


On Thu, 21 Nov 2002 16:28:12 +0100, Jesse Lawrence wrote:

> 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.
 
When you do header[0], your 'header' list is empty so you get an error
because your index is not valid, and python won't create it for you
on the fly.

Just change your code to and I think this will be fine:
    ...
    header = []
    for r in row:
       header.append(r[0])
    return header

Pedro



More information about the Python-list mailing list