Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tidy up list comprehensions pythonically

Tags:

python

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?

like image 838
sof Avatar asked Feb 17 '26 07:02

sof


1 Answers

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.

like image 197
chepner Avatar answered Feb 19 '26 21:02

chepner