python

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.

Read more »

dailygrind desklet

tung's picture

Don't be the example, multiple entries can appear in each section

dailygrind is an adesklets widget that keeps you informed of repetitive tasks. Things that you do every day, you need every week, every month, every year, or even just a once-off, are all shown in a small box on your desktop.

Read more »
Syndicate content