From time to time, I find that I need a function to return +1, 0, or -1 representing the sign of a value: +1 or -1 for positive or negative values, or 0 for a zero value. I remember learning this as the sgn function in high school. Python’s standard lib leaves this out, but does supply cmp as a built-in, so the standard approach would probably be to define sgn using:

`sgn = lambda x : cmp(x,0)`

I found a nice website of Bit-Twiddling Hacks the other day, and it had a nice alternative for sgn, which in Python would be:

`sgn = lambda x : (x>0) - (x<0)`

The elegance of this appeals to me and I did a quick timing pass:

`C:\Users\Paul>python -m timeit "[cmp(x,0) for x in (-100,0,14)]"`

1000000 loops, best of 3: 0.645 usec per loop

```
```

`C:\Users\Paul>python -m timeit "[lambda x:x>0 - x<0 for x in (-100,0,14)]"`

1000000 loops, best of 3: 0.496 usec per loop

So by cutting out the repeated function calls to cmp, this also has the benefit of being just a tad faster.

### Like this:

Like Loading...

*Related*

#1 by

Anton Chikinon May 13, 2011 - 3:45 amParsing namespaces takes the most time. you can just say:

>>>local_cmp = cmp

>>>[local_cmp(x,0) for x in (-100,0,14)]