Should You Be Using Python’s Walrus Operator? (Yes. and Here’s Why)
martinheinz.dev
martinheinz.dev
vs.
y = func(x)
result = [y, y*2, y*3]
The latter seems vastly superior to me. Author says > You might say, "I can just add y = func(x) before the list declaration and I don't need the walrus!", you can, but that's one extra, unnecessary line of code and at first glance - without knowing that func(x) is super slow - it might not be clear why the extra y variable needs to exist.
And I think that's stupid
Second example result = [y for x in data if (y := func(x))]
Author says alternative is result = [func(x) for x in data if func(x)]
I say it is
result = [func(x) for x in data]
result = [x for x in result if x] # filter out 0s
{x:y
for x in data
if (y := f(x))}
Benefit there is that you only iterate over data once (possibly exhasting it) and you only allocate the result list. In 3.9, that takes some wrangling and extra tuple creation/unpacking. pairs = ((x,func(x)) for x in data)
result = {x:y for x,y in pairs if y}I know we dont get paid by LOC but this recent obsession with compressing everything into a single line is off-putting.
x = 5
y = x + 1
plot(x, y)
I try to just have each line do one simple thing.