I would like to turn this code into a list comprehension:
l = list()
for i in range(10):
j = fun(i)
if j:
l.append(j)
Meaning that I'd like to add only truthy fun()
result values to the list. Without the truthy check of that function call, the list comprehension would be:
l = [fun(i) for i in range(10)]
Adding a if fun(i)
to the list comprehension would cause two evaluations of fun()
per iteration (actually, not always it seems!), thus causing unintended side effects if fun()
is not pure.
Can I capture the result of fun(i)
and use it in that same comprehension, essentially adding the if j
? (Related question here)