Create a temporary dict to store the values. Then create a function that uses this dict as a cache, and use this function in a list comprehension, for example:
obj_cache = {} def cache_get (target, key): if (target, key) not in obj_cache: obj_cache[(target, key)] = target.get(key) return obj_cache[(target, key)] resources = [cache_get(obj, "file") for obj in iterator if cache_get(obj, "file") != None]
In addition, you probably already know this (and if so, please ignore this answer), but if obj.get ("file") does not make a database call, does not open the file, does not make a request over the network, or does something else potentially expensive, calling it twice per iteration, rather than once, is probably harmless, since you only add O (n) to your value.
source share