Local variable definition in Python list comprehension

Eryk Sun eryksun at gmail.com
Thu Sep 1 12:34:07 EDT 2022


On 9/1/22, James Tsai <jamestztsai 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)]


More information about the Python-list mailing list