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?

ofir1080
  • 105
  • 1
  • 5
  • 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` – DisappointedByUnaccountableMod Aug 20 '21 at 09:10
  • 5
    I added some parentheses: `x if True else x, x` is the same as `((x if True else x), x)`. – Matthias Aug 20 '21 at 09:11
  • you are correct. So it is interpreted as `return (x if True else x), x`. Sould have noticed. Thanks – ofir1080 Aug 20 '21 at 09:12
  • Does this answer your question? [Putting a simple if-then-else statement on one line](https://stackoverflow.com/questions/2802726/putting-a-simple-if-then-else-statement-on-one-line) – bad_coder Aug 21 '21 at 14:15

2 Answers2

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
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
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

Pranav Asthana
  • 892
  • 1
  • 9
  • 21