0

Is there some sort of let syntax for a variable in the python for comprehension? What I mean is a way to bind a newly named variable like an iteration, but without actually iterating anything.

data = [w for y in f() let z = g(y) if z > 0 for w in h(z)]

This can be done in Python in a more cryptic way of course by making a singleton list, [g(y)], which is what I do, being not a python expert.

data = [w for y in f() for z in [g(y)] if z > 0 for w in h(z)]

The let syntax exists for the equivalent of for comprehensions in Common Lisp, Clojure, and Scala, so I wondered whether there is corresponding syntax in Python as well.

Jim Newton
  • 594
  • 3
  • 16

1 Answers1

0

strating from python 3.8 you can try the assignment operator := like this:

data = [w for y in f() if (z:=g(y)) > 0 for w in h(z)]

if there is no actual need for this variable, you can just write:

data = [w for y in f() if g(y) > 0 for w in h(g(y))]

for more info refer: assignment expressions

Daniel
  • 1,895
  • 9
  • 20
  • 1
    yes, but but in your suggestion I have to call `g(y)` twice, right? Which means there IS a need to bind the value of `g(y)` to a variable. – Jim Newton Aug 20 '21 at 12:55
  • 1
    correct, the assignment expressions are only available from version 3.8, for previous versions I guess it's better to use **your** second option with the singleton list. – Daniel Aug 20 '21 at 12:57