Reputation: 145
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
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
Reputation: 71570
The reason is that the code:
def func(x):
return x if True else x, x
Will run in the following order:
return x if True else x
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