Local variable definition in Python list comprehension

Peter J. Holzer hjp-python at hjp.at
Thu Sep 1 18:11:56 EDT 2022


On 2022-09-01 13:33:16 -0700, James Tsai wrote:
> 在 2022年9月1日星期四 UTC+2 18:34:36,<ery... at gmail.com> 写道:
> > On 9/1/22, James Tsai <james... at gmail.com> wrote: 
> > > 
> > > I find it very useful if I am allowed to define new local variables in a 
> > > list comprehension. For example, I wish to have something like 
> > > [(x, y) for x in range(10) for y := x ** 2 if x + y < 80], or 
> > > [(x, y) for x in range(10) with y := x ** 2 if x + y < 80]. 
> > > 
> > > For now this functionality can be achieved by writing 
> > > [(x, y) for x in range(10) for y in [x ** 2] if x + y < 80].
> > You can assign a local variable in the `if` expression. For example: 
> > 
> > >>> [(x, y) for x in range(10) if x + (y := x**2) < 30] 
> > [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]
> 
> Yeah this works great but like [(x, y) for x in range(10) for y in
> [x**2]] I written before, is kind of a hack. And if initially I do not
> need an "if" condition in the list comprehension, this becomes less
> convenient. I still can write 
> >>> [(x, y) for x in range(10) if (y := x**2) or True]

In that case 
    [(x, x**2) for x in range(10)]
seems to be somewhat more readable.

I would also say that
    [(x, x**2) for x in range(10) if x + x**2 < 80]
doesn't really seem worse than any of the variants with y in it.
(Yes, I get that your real duplicated expression is probably a bit more
complex than `x**2`, but by the time a temporary variable really
improves readability it's probably a good time to split that across
multiple lines, too.)

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20220902/161dc0c6/attachment.sig>


More information about the Python-list mailing list