Skip to content Skip to sidebar Skip to footer

Avoid Computing The Same Expression Twice In List Comprehension

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

Solution 1:

Compute the results beforehand and iterate over them

new_list = [x for x in map(f, old_list) if x !=0]

Moreover, since map computes the result per element when the element is accessed this is just one loop.

Solution 2:

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]

Solution 3:

in Python 3.8 we'll have the "walrus operator" and be able to do just that!

[y for x in old_list if (y := f(x)) != 0]

Solution 4:

You could use a filter to remove results:

deff (x):
  return x * 2

old_list = [0, 1, 2, 3]

new_list = filter(lambda x: x != 0, [f(x) for x in old_list])

for x in new_list:
  print(x)

See it working here.

Alternatively you could memoize the function so as to prevent ever having to compute the same result twice:

deff (x):
  return x * 2defmemoize(f):
    memo = {}
    defhelper(x):
        if x notin memo:
            print("Computing result for %s" % x)        
            memo[x] = f(x)
        return memo[x]
    return helper

memF = memoize(f)

old_list = [0, 1, 2, 3]

new_list = [memF(x) for x in old_list if memF(x) != 0]

for x in new_list:
  print(x)

Which is available here.

Post a Comment for "Avoid Computing The Same Expression Twice In List Comprehension"