Comprehensions in Python
Posted on 2024-02-18 by xkollar
.Python’s comprehensions (list, generator, dictionarry) are neat,
however coming from Haskell I miss let
.
= [ item | itemId <- ids, let item = getItem itemId, isFun item ] funItems
In the meantime, I have seen in python
= [ get_item(item_id) for item_id in ids if is_fun(get_item(item_id)) ] fun_items
Needless to say, even without get_item
being an expensive operation,
this feels bad. After thinking about it for a while I came up with and
alternative.
= [ item for item_id in ids for item in (get_item(item_id),) if is_fun(item) ] fun_items
Though it is a bit longer 🤔. You win some, you lose some, I guess. 🤷