list comprehensions value assignment syntax error

Steve Holden sholden at holdenweb.com
Tue Jan 7 19:29:53 EST 2003


"Gerrit Holl" <gerrit at nl.linux.org> wrote in message
news:mailman.1041983459.23262.python-list at python.org...
> Hi,
>
> I am trying to assign to a list item using list comprehensions, but this
> raises a SyntaxError:
>
> >>> [l[i] = chr(i) for i in range(256)]
>    File "<stdin>", line 1
>        [l[i] = chr(i) for i in range(256)]
>              ^
> SyntaxError: invalid syntax
>
> Why?
>
> Do I really have to abandon list comprehensions or do this?:
>
> >>> [l.__setitem__(i, chr(i)) for i in range(256)]
>

Well, I suppose my first question was "why?".

Do you want "l" to become a list of 256 bytes? In that case, what you want
is

    l = [chr(i) for i in range(265)]

and you're done. Assignment is a *statement* in Python, not an expression.
You've been around this group long enough to know where to consult the FAQ,
which I suggest you do if you *really* want to change list elements inside a
comprehension (which is an *expression*).

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Bring your musical instrument to PyCon!    http://www.python.org/pycon/
-----------------------------------------------------------------------







More information about the Python-list mailing list