0

Given the following trivial function:

def func(x):
     return x if True else x, x

Why is func(1) returns the tuple (1, 1), even if the desired results would be the identity?

However, note that the following:

def func(x):
    return x if True else (x, x)

Does return the desired integer type. Can anyone explain such behavior and why this happens?

3
  • 5
    A tuple is returned because your return statement has two values separated by a , - i.e. it’s a tuple, always. Might look clearer as (x if True else x), x Commented Aug 20, 2021 at 9:10
  • 5
    I added some parentheses: x if True else x, x is the same as ((x if True else x), x). Commented Aug 20, 2021 at 9:11
  • you are correct. So it is interpreted as return (x if True else x), x. Sould have noticed. Thanks Commented Aug 20, 2021 at 9:12

2 Answers 2

2

The reason is that the code:

def func(x):
     return x if True else x, x

Will run in the following order:

  1. return x if True else x
  2. x

And with the comma separator, it becomes a tuple, example:

>>> 1, 1
(1, 1)
>>> 

It's not because the condition went to the else statement, it's because there is no parenthesis.

If you make the else statement give 100:

def func(x):
     return x if True else 100, x

func(1) will still give:

1, 1

Not:

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

Comments

0

below function

def func(x):
 return x if True else x, x

is same as

def func(x):
     return x , x

which return (1,1) when called as func(1). If else is useless here as the condition is always True

However the function

def func(x):
return x if True else (x, x) 

is same as

def func1(x):
return x 

which return 1 if called as func(1) as expected

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.