[Python-ideas] Temporary variables in comprehensions

Kyle Lahnakoski klahnakoski at mozilla.com
Fri Feb 23 12:34:40 EST 2018


I believe list comprehensions are difficult to read because they are not
formatted properly. For me, list comprehension clauses are an
expression, followed by clauses executed in the order. Any list
comprehension with more than one clause should be one-line-per clause.

Examples inline:

On 2018-02-15 19:57, Steven D'Aprano wrote:
> Where should the assignment go? [(y, y**2) let y = x+1 for x in (1, 2,
> 3, 4)] [(y, y**2) for x in (1, 2, 3, 4) let y = x+1] 

Since y is a function of x, it must follow the for clause:

> [
>     (y, y ** 2)
>     for x in (1, 2, 3, 4)
>     let y = x + 1
> ]

> How do they interact when you have multiple loops and if-clauses? [(w,
> w**2) for x in (1, 2, 3, 4) let y = x+1 for a in range(y) let z = a+1
> if z > 2 for b in range(z) let w = z+1] 

They are applied in order:

> [
>     (w, w**2)
>     for x in (1, 2, 3, 4)
>     let y = x+1
>     for a in range(y)
>     let z = a+1
>     if z > 2
>     for b in range(z)
>     let w = z+1
> ]

which is a short form for:

> def stuff():
>     for x in (1, 2, 3, 4):
>         y = x+1
>         for a in range(y):
>             z = a+1
>             if z > 2:
>                 for b in range(z):
>                     w = z+1
>                     yield (w, w**2)
>
> list(stuff())




More information about the Python-ideas mailing list