Local variable definition in Python list comprehension

Dan Stromberg drsalists at gmail.com
Fri Sep 2 19:43:03 EDT 2022


On Thu, Sep 1, 2022 at 9:16 AM Chris Angelico <rosuav at gmail.com> wrote:

> On Fri, 2 Sept 2022 at 02:10, James Tsai <jamestztsai 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.
>
So true!

I like list comprehensions and generator expressions, but sometimes I end
up regretting their use when there's a bug, and I have to convert one to a
for loop + list.append in order to debug.


More information about the Python-list mailing list