Unpack a list with ternary operator
Question:
I stumbled upon a weird behaviour when I want to unpack a list only if condition is true.
How can I use the unpacking (*) based on a condition?
Example:
def foo1(x1, x2):
print(x1, x2)
def foo2(x):
print(x)
l = [7,8]
foo1(*l if True else l) # this works
foo2(*l if False else l) # this does not work
foo1(l if not True else *l) # this does not work
Answers:
That’s not parsed as choosing between *l
on the left and l
on the right. l if True else l
is evaluated, and then the result is unpacked, unconditionally.
There’s no way to have a function call expression conditionally either unpack or not unpack an argument. Something’s getting unpacked if you put a *
there. What you can do is wrap l
in another list and unpack that:
foo(*(l if condition else [l]))
I stumbled upon a weird behaviour when I want to unpack a list only if condition is true.
How can I use the unpacking (*) based on a condition?
Example:
def foo1(x1, x2):
print(x1, x2)
def foo2(x):
print(x)
l = [7,8]
foo1(*l if True else l) # this works
foo2(*l if False else l) # this does not work
foo1(l if not True else *l) # this does not work
That’s not parsed as choosing between *l
on the left and l
on the right. l if True else l
is evaluated, and then the result is unpacked, unconditionally.
There’s no way to have a function call expression conditionally either unpack or not unpack an argument. Something’s getting unpacked if you put a *
there. What you can do is wrap l
in another list and unpack that:
foo(*(l if condition else [l]))