Here is a code snippet that shows the code I would like to optimize:
result = [(item, foo(item))
for item in item_list
if cond1(item) and cond2(foo(item))]
In the above snippet I call foo(item)
twice. I can't think of a way to iterate over the list only once maintain both item
and foo(item)
for the conditional and the result list.
That is, I would like to keep item
and foo(item)
without having to loop over the list twice and without having to call foo(item)
twice.
I know I can do it with a second nested list comprehension:
result = [(item, foo_item)
for item, foo_item in [(i, foo(i)) for i in item_list]
if cond1(item) and cond2(foo_item)]
but that appears to loop through item_list
twice which I would like to avoid.
So the first example calls foo
twice per list item. The second example loops through the list twice (or appears to). I'd like to loop one time and call foo
once for each item.