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

Time:04-24

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:

    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?

CodePudding user response:

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.

  • Related