Problem with list assignment

Alex Martelli aleax at aleax.it
Thu Nov 21 13:03:53 EST 2002


Jesse Lawrence wrote:
  ...
>    # here's the problem area:
>    header = []
>    i = 0;
>    for r in row:
>       header[i] = r[0]
>       i = i + 1
>    return header

change this snippet to, for example:
    header = []
    for r in row:
        header.append(r[0])
    return header
or more concisely to the single line:
    return [r[0] for r in row]

You can't assign to items of a list that do not yet exist: you can append 
to the list, or build the list in one gulp with the list-comprehension 
construct I've used in the "single line" version.


Alex




More information about the Python-list mailing list