Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid computing the same expression twice in list comprehension [duplicate]

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.

like image 369
vlemaistre Avatar asked Aug 24 '26 08:08

vlemaistre


1 Answers

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]
like image 196
hiro protagonist Avatar answered Aug 26 '26 23:08

hiro protagonist