2 ms·
While 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 :
by klyrs 4y ago
While 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}