ofir1080
ofir1080

Reputation: 145

One-line if-else in Python: interpreting behavior

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?

Upvotes: 0

Views: 75

Answers (2)

Pranav Asthana
Pranav Asthana

Reputation: 912

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

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71570

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

Upvotes: 2

Related Questions