Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unpack a list with ternary operator

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading