list comprehensions value assignment syntax error
Gerrit Holl
gerrit at nl.linux.org
Wed Jan 8 09:56:00 EST 2003
Hans Nowak schreef op woensdag 8 januari om 01:47:01 +0000:
> Gerrit Holl wrote:
>
> >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?
>
> The first part of a list comprehension must be an expression. An assignment
> like l[i] = chr(i) is a statement.
Ah, I see. Thank you for your help, I did not realise this.
> As others have pointed out, you can write this as
>
> l = [chr(i) for i in range(256)]
>
> or, if you don't want to rebind l to a new object,
>
> l[:] = [chr(i) for i in range(256)]
I now realise my problem did only rise because my list is 2-dimensional,
e.g. I can do:
>>> L[3][2:7] = range(5) # or with list comprehension instead of range(5)
...but I can't do:
>>> L[2:7][3] = range 5
...or of course this does something very different.
yours,
Gerrit.
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
http://www.sp.nl/
More information about the Python-list
mailing list