Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do a function call in a list comprehension only once if needed twice [duplicate]

Here a generic Python question about generators/list comprehension.

For a given iterable x I need a list comprehension which looks like this:

[ flatten(e) for e in x if flatten(e) != '' ]

The function flatten is potentially expensive, so it would be nice to call it only once. Is there a way to do this in an expressive one-liner?

like image 813
halloleo Avatar asked Dec 13 '16 00:12

halloleo


1 Answers

Nest a generator:

[item for item in (flatten(e) for e in x) if item != '']

Or:

[item for item in map(flatten, x) if item != '']
like image 157
TigerhawkT3 Avatar answered Sep 22 '22 08:09

TigerhawkT3