Python inline conditionals

tung's picture

I used to always use this:

x = cond and y or z

Resulting in setting x to y if cond was True, or to z if not. It does some funny things if you throw zeros into the mix, but it's usually good.

Over here is the 'proper' Python way of doing things:

x = y if cond else z

I didn't even know that existed.

Here's a trick with tuples, similar to the first:

x = (y, z)[cond]

It works because True and False in Python can be treated as 1 and 0, respectively. Watch out though, it still evaluates both y and z.