4 ms·
result = [y := func(x), y*2, y*3] 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 ad
by spywaregorilla 4y ago
result = [y := func(x), y*2, y*3]
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
- klyrs 4y agoWhile I'm generally of the opinion that walrus shouldn't be used until py3.9's end of life, I'd steelman the second example: {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}
- ahurmazda 4y agoWell said! I know we dont get paid by LOC but this recent obsession with compressing everything into a single line is off-putting.
- kbelder 4y agoI tend to write code like I used to write assembly. x = 5 y = x + 1 plot(x, y) I try to just have each line do one simple thing.
- p5a0u9l 4y agoYour criticism sense I to leave out the motivation that the walrus operator in this case leads to an elegant recursion. Edit. Not a recursion, but a reuse of the variable while still getting able to retain a list comprehension.