[Python-ideas] Assignments in list/generator expressions

Jim Jewett jimjjewett at gmail.com
Wed Apr 13 15:25:03 CEST 2011


On 4/12/11, Stephen J. Turnbull <stephen at xemacs.org> wrote:
> Greg Ewing writes:
>  > Stephen J. Turnbull wrote:

>  > >  >    ys = [y for x in xs letting y = f(x) if y]

>  > > I'm sorry, but I read that three times and it parsed as "y gets
>  > > undefined if it is false" every time.

Me too ... but then I try to figure out what to do with an undefined,
so the eventual answer is either an error, or what you really wanted
in the first place.

>  > In that case, would you prefer this?

>  >    ys = [y for x in xs if y given y = f(x)]

I would ... but I don't actually *like* it, I just find it less problematic.

> Yes, very much.  I would also prefer
>
>     ys = [y for x in xs given y = f(x) if y]

> to the "letting" version, though that is harder to read (for me) than
> the version with the assignment at the end of the expression.

I find this less objectionable still.  It improves more if the "given"
clause is on a separate line.

I'm not sure there *is* a likable way to put the comprehension, the
temporary assignment, and the filter into one unbroken thought.

-jJ



More information about the Python-ideas mailing list