Woah! I was all ready to disagree with you, saying 'only for Boolean arguments'. In years of writing python I really thought `__and__`/`__or__` returned Boolean. (Of course they can, but for builtins I mean.)
Is this official, encouraged syntax? It looks like it's just exploiting short-circuit evaluation. `bar && foo || baz` works in Javascript as well for example.
In fact, nearly 20 years ago PEP 308 ("Conditional Expressions") was made so people wouldn't need to resort to this sort of syntax - https://www.python.org/dev/peps/pep-0308/ .
> In many cases you can mimic a ? b : c with a and b or c, but there’s a flaw: if b is zero (or empty, or None – anything that tests false) then c will be selected instead. In many cases you can prove by looking at the code that this can’t happen (e.g. because b is a constant or has a type that can never be false), but in general this can be a problem.
> Tim Peters (who wishes it was Steve Majewski) suggested the following solution: (a and [b] or [c])[0].
I have seen it a lot of code over the years, sometimes referred to as "shorthand ternary" or the "and-or-trick". In Python and/or do not return a boolean, but one of its input arguments. So I am going to say it is official syntax, but I don't know to what extent it's encouraged
It does short circuit, your logic is just purposely fragile. If you reverse the variables it will print Empty, because the and statement evaluates left to right and stops if one of the arguments is falsey.
print(len(foo) > 0 and foo[0] or "Empty")
And since len can't give negative numbers the more Pythonic way to do it would be like this. Even though I generally prefer normal if blocks.
print(len(foo) and foo[0] or "Empty")
edit: I do agree that you should probably avoid doing this at all, because it is easy to introduce subtle bugs.