Possible Duplicate:
Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?
I noticed today that the following works using python 2.6 (Cpython)...
>>> a=[100,200]
>>> a[True]
200
>>> a[False]
100
Is this portable to other python implementations (e.g. is True
/False
guaranteed to inherit from int? Is True
guaranteed to evaluate to 1 instead of some other non-zero number?) Is there any situation where this would be useful? It seems like it could be used as another form of a ternary operator, but I don't know how much is gained there...
It is part of the language specification, so any Python implementation should implement the booleans as equivalent to the integers.
Yes -- this is guaranteed -- with the caveat that
True
andFalse
may be reassigned; but that doesn't affect the results of boolean operations. (Thanks to Ignacio for the documentary proof.) In fact, back when there was no ternary operator, this was one of the methods used to emulate it. Nowadays, if you want a ternary operator, use the ternary operator. But sometimes this construct is still useful. For example:You can do this with a dictionary as well. It has a ternary operator equivalent...
But I actually find the list-indexing version easier to read, at least in this case. YYMV.