Output of True and []

305 Views Asked by At

I was wondering why
True and []
returns [] instead of False

Is the expression a syntactic sugar ?

2

There are 2 best solutions below

0
On BEST ANSWER

The answer is found at 5.10. Boolean Expressions:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

5
On

This syntactic sugar is sometimes used as a ternary operator in Python

C++: someVar = someCondition ? valueIfTrue : valueIfFalse;
Python: someVar = someCondition and valueIfTrue or valueIfFalse 

Edit: It turns out, as per comments :), this is a major pitfall in Python and should be replaced by

someVar = valueIfTrue if condition else valueIfFalse