I am using a function in a list comprehension and an if function:
new_list = [f(x) for x in old_list if f(x) !=0]
It annoys me that the expression f(x) is computed twice in each loop.
Is there a way to do it in a cleaner way? Something along the lines of storing the value or including the if statement at the beginning of the list comprehension.
you could use a generator expression (in order to avoid creating an unnecessary list) inside your list comprehension:
new_list = [fx for fx in (f(x) for x in old_list) if fx != 0]
starting from python 3.8 you will be able to do this:
new_list = [fx for x in old_list if (fx := f(x)) != 0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With