Page 1 of 1

Why does split method behave differently in an inline if-else statement?

Posted: Tue May 18, 2021 10:13 am
by MicroP_W691
I'm a bit confused why the behaviour of the split statement is different between two use cases, and wondered what I may have overlooked?

This works the way I'd expect it to:

Code: Select all

>>> u = 'm/s^2'
>>> if '^' in u:
        a, b = u.split('^')
>>> a
'm/s'
>>> b
'2'
Now I tried to simplify this into a single statement, but instead got this behaviour:

Code: Select all

>>> u = 'm/s^2'
>>> a,b = u.split('^') if ('^' in u) else u,''
>>> a
['m/s', '2']
>>> b
''
What causes this difference?

Re: Why does split method behave differently in an inline if-else statement?

Posted: Tue May 18, 2021 10:26 am
by MicroP_W691
Oops, I figured out the issue, user error! The object after the last comma is being assigned to the 'b' variable, which make sense based on how the line would tokenised and parsed by the interpreter.

The correct implementation should be:

Code: Select all

>>> a,b = u.split('^') if ('^' in u) else (u,'')
This returns a + b as expected.

Re: Why does split method behave differently in an inline if-else statement?

Posted: Tue May 18, 2021 10:29 am
by SpotlightKid
You are missing some parentheses (and have others, which are not necessary).

Correct:

Code: Select all

a, b = u.split('^') if '^' in u else (u,'')
Your original code gets parsed like this:

Code: Select all

a, b = (<ternary-expression>, '')
And then tuple unpacking and assignment assigns the result of the ternary expression (the first element of the tuple) to a and the empty string (the second element) to b.

Lesson: commas are very important in Python :)

Re: Why does split method behave differently in an inline if-else statement?

Posted: Tue May 18, 2021 10:50 am
by pythoncoder
This is a common "gotcha" and it's down to the way Python parses the code. It is effectively executed as

Code: Select all

a,b = (u.split('^') if ('^' in u) else u),''
rather than

Code: Select all

a,b = u.split('^') if ('^' in u) else (u,'')

Re: Why does split method behave differently in an inline if-else statement?

Posted: Tue May 18, 2021 3:27 pm
by MicroP_W691
Thanks guys :)