Archive

Archive for October, 2007

Some nice things to know about operators in python

October 11th, 2007

There are a few operator related things that aren’t (as far as I know) common knowledge in python.

The first is the not in and is not operators. Basically, not is normally a unary operator and in and is are binary. Hower these two operations are valid

foo not in bar # same as "not foo in bar"
foo is not bar # same as "not foo is bar"

This is not obvious since not in this case doesn’t do unary negation but rather forms a new binary operator together with is or in.

Another cool thing is chaining comparisons. In C this would evaluate to False (or rather 0 since C lacks booleans).

int foobar = 3>2>1; // in C evaluates to (3>2)>1 = 1 > 1 = 0

In python however this will return True! This is because of python evaluating this chaining the same way as it is used in mathematics and so on.

foobar = 3>2>1 # in python evaluates to True

Basically this is translated by python to

foobar = 3>2 and 2>1

Both of these things might be common knowledge but I didn’t know about it and someone else might not as well.

buffi Programming & scripting, Python