Skip to content

Comment on Python does support if-else in lambdas...parent

Comments

The danger here is that this will fall through to the falseaction if trueaction returns a false result ("", False, 0, None, [], {}, etc). For example, this will evaluate to "etc":

  True and "" or "etc"
So people started doing this instead, as [False] is still 'true' (non-empty lists are 'true' in Python):
  (condition and [trueaction] or [falseaction])[0]
... which is a bit crufty. So this was added:
  trueaction if condition else falseaction

Ah, that is much better. I've been learning from Dive Into Python which I know is a tad dated, and Pilgrim (sort of) endorses the and...or method.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.