Is there any legitimate use of list[True], list[False] in Python?

In the past, some people have used this behaviour to produce a poor-man’s conditional expression:

['foo', 'bar'][eggs > 5]  # produces 'bar' when eggs is 6 or higher, 'foo' otherwise

However, with a proper conditional expression having been added to the language in Python 2.5, this is very much frowned upon, for the reasons you state: relying on booleans being a subclass of integers is too ‘magical’ and unreadable for a maintainer.

So, unless you are code-golfing (deliberately producing very compact and obscure code), use

'bar' if eggs > 5 else 'foo'

instead, which has the added advantage that the two expressions this selects between are lazily evaluated; if eggs > 5 is false, the expression before the if is never executed.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)