2

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?

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It's probably easier to explain it as: a, b = (my_func() if direction == 'forward' else 30), 40 OP, try putting the final 30, 40 within parens: a, b = my_func() if direction == 'forward else (30, 40)
This was very well explained from you and Jake. I tried the parens at the end and it indeed works now. So, many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.