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

Why unpacking doesn't work correctly when using an one line if-else statement

I’m very new to Python and came to a strange behaviour while tested my code. I’m searching over a tree and gather informations, depending on the direction i’m searching the tree.

    def my_func():
        return (10,20)

    direction = 'forward'

    if direction == 'forward':
        a, b = my_func()  
    else: 
        a, b = 30,40

    print (f'Direction is: {direction}\nThe value of a is: {a} \nThe value of b is: {b}')

This gives me the expected result:

    Direction is: forward    Direction is: backward
    The value of a is: 10    The value of a is: 30 
    The value of b is: 20    The value of b is: 40

But if i use an one-line if-else-condition the result is strange:

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

    a, b = my_func() if direction == 'forward' else 30,40

This gives me the following result:

    Direction is: forward          Direction is: backward    
    The value of a is: (10, 20)    The value of a is: 30      
    The value of b is: 40          The value of b is: 40

Can anyone explain to me why unpacking doesn’t work in this case (forward search) and why b gets the value from the else branch?

>Solution :

It isn’t unexpected. You set a to my_func() if direction == 'forward' else 30 and b to 40. This is because the unpacking is done before the ternary operator. Thus, a will take the result of the one line if else condition and b will take the value 40.

If you want to fix it, do a, b = my_func() if direction == 'forward' else (30, 40)

EDIT: credit to @Jake, who commented at the same time I edited.

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