Local variable definition in Python list comprehension
James Tsai
jamestztsai at gmail.com
Thu Sep 1 16:26:28 EDT 2022
在 2022年9月1日星期四 UTC+2 18:16:03,<Chris Angelico> 写道:
> On Fri, 2 Sept 2022 at 02:10, James Tsai <james... at gmail.com> wrote:
> >
> > Hello,
> >
> > 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].
> >
> > Is it worthwhile to add a new feature like this in Python? If so, how can I propose this to PEP?
> Not everything has to be a one-liner.
>
> ChrisA
No but very often when I have written a neat list/dict/set comprehension, I find it very necessary to define local variable(s) to make it more clear and concise. Otherwise I have to break it down to several incrementally indented lines of for loops, if statements, and variable assignments, which I think look less nice.
More information about the Python-list
mailing list