i=2; lst=[i**=2 while i<1000]

bonono at gmail.com bonono at gmail.com
Tue Dec 6 09:50:09 EST 2005


Daniel Schüle wrote:
> D H wrote:
> > bonono at gmail.com wrote:
> >
> >>> You can use i**=2 for i in range(1000) instead
> >>
> >>
> >>
> >> I don't think one can use assignment in list comprehension or generator
> >> expression. The limitation is very much like lambda.
> >>
> >
> > i**2
>
> lst=[i**2 for i in range(1000)]
>
> you will get a list with 1000 items
> [0,1,4,9 ... ]
>
> is not the same as
>
> i,lst=2,[]
> while i<1000:
> 	i**=2
> 	lst.append(i)
>
> here you get [4,16,256,65536]
> only 4 items
>
You want a combination of takewhile and scanl and filter. For this
particular snippet, I think a simple loop is cleaner. I am bias towards
one-liner but for this case, explicit loop beats it. Just define a
short function.




More information about the Python-list mailing list