Here comes a Pythonic Encounter that kept me entertained for a while debugging until I realised what as actually going… :-)
I’ve been using Python conditional expressions for a while now, at least the simplest in the form of:
expression1 if condition else expression2
However, yesterday I was faced with a situation that although now looks very obvious on the moment of typing this little detail was not sparking in my mind.
I wanted to make use of conditional expressions to pass two lists with empty strings to variables b and c in the case the condition was evaluated to False. However, I was receiving an unexpected output (and took me a while to understand from where and why).
So, what is wrong with the following expression?
Why was the two lists with empty strings inside not being passed to b and c? It was only after I posted a thread in Python-forum.io that a spark light on my mind!
Solution: The conditional expression ended in the comma (,), so the result from the conditional was being assigned to b and the [“”] to c. Hence, the following code gave the expected output:
And that’s it, my yesterday Pythonic encounter. The solution was quite easy and obvious, but, interesting nonetheless. Take home message, sometimes is better to enclose expressions in brackets, it corrects and clarifies things :-P