Local variable definition in Python list comprehension

James Tsai jamestztsai at gmail.com
Thu Sep 1 16:33:16 EDT 2022


在 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]

But I wonder if Python could have a specific syntax to support this.


More information about the Python-list mailing list