FP like Haskell can bind a (var) name trivially e.g:
[(g y, h y) | x <- mylist, let y = f x]
Python does it possibly below:
mylist = [f(x) for x in mylist]
mylist = [(g(y), h(y)) for y in mylist]
Walrus assignment in Python 3.8 seems a hack to simplify list comprehensions :
[(y := f(x), g(y), h(y)) for x in mylist]
What is so far considered pythonic way in this case?
The correct use of the walrus operator to create 2-tuples would be
mylist = [(g(y:=f(x)), h(y)) for x in mylist]
which, yes, is even more horrendous than the 3-tuple version. If you want to forgo the walrus operator, use the version which := was supposed to obviate:
mylist = [(g(y), h(y)) for x in mylist for y in [f(x)]]
or more simply
mylist = [(g(y), h(y)) for y in map(f, mylist)]
I would not say the walrus operator is always so ungainly, but it seems to be more trouble than it is worth here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With