Example:
final_list = []
for item in temp_list:
if foo(item): #this function is calling API or doing some heavy computation task
final_list.append(item)
Firstly, we can use list comprehension(which is faster than writing .append()
[item for item in temp_list foo(item)]
And finally memoize the function call.
If you do not know what memoization is : Read about memoization.
memoization_dict = {}
def memoize(item):
if val not in memoization_dict:
memoization_dict[item] = foo(item)
return memoization_dict[item]
final_list = [memoize(item) for item in temp_list if memoize(item)]