list comprehensions value assignment syntax error

Hans Nowak wurmy at earthlink.net
Wed Jan 8 01:43:19 CET 2003


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)

Cheers,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html





More information about the Python-list mailing list