list comprehensions value assignment syntax error

Peter Abel p-abel at t-online.de
Wed Jan 8 21:09:46 CET 2003


Hans Nowak <wurmy at earthlink.net> wrote in message news:<3E1B74F8.2020200 at earthlink.net>...
> 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.
> 
> > Do I really have to abandon list comprehensions or do this?:
> > 
> >>>>[l.__setitem__(i, chr(i)) for i in range(256)]
> 
> This looks like an abuse of list comprehensions, doing something with them that 
> they're not really meant for.
> 
> 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)]
> 
> Or use a for loop, of course:
> 
>    l = []
>    for i in range(256):
>        l[i] = chr(i)
> 
Sorry Hans, your last statement result in an IndexError:
Traceback (most recent call last):
  File "<interactive input>", line 2, in ?
IndexError: list assignment index out of range

You can't adress an element that isn't initiated!

The right way is:
>>> l=[]
>>> for i in range(256):
... 	l.append(chr(i))
... 	

And I think the shortest Code is:
>>> l=map(chr,range(256))

Best regards
Peter
> Cheers,




More information about the Python-list mailing list