How to set local variable in list comprehension?
Use nested list comprehension:
[x for x in [map_to_obj(v) for v in v_list] if x]
or better still, a list comprehension around a generator expression:
[x for x in (map_to_obj(v) for v in v_list) if x]
A variable assignment is just a singular binding:
[x for v in l for x in [v]]
This is a more general answer and also closer to what you proposed. So for your problem you can write:
[x for v in v_list for x in [map_to_obj(v)] if x]
Starting in Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), it's possible to use a local variable within a list comprehension in order to avoid calling the same function twice.
In our case, we can name the evaluation of map_to_obj(v)
as a variable o
while using the result of the expression to filter the list; and thus use o
as the mapped value:
[o for v in [v1, v2, v3, v4] if (o := map_to_obj(v))]