Spaceship operator in Python
Some programming languages, such as Perl, have an infix operator <=> that returns a three-state comparison. The expression
a <=> b
evaluates to -1, 0, or 1 depending on whether a < b, a = b, or a > b. You could think of <=> as a concatenation of <, =, and >.
The <=> operator is often called the spaceship operator" because it looks like Darth Vader's ship in Star Wars.
Python doesn't have a spaceship operator, but you can get the same effect with numpy.sign(a-b). For example, suppose you wanted to write a program to compare two integers.
You could write
from numpy import sign def compare(x, y): cmp = ["equal to", "greater than", "less than"][sign(x-y)] print(f"{x} is {cmp} {y}.")
Here we take advantage of the fact that an index of -1 points to the last element of a list.
The sign function will return an integer if its argument is an integer or a float if its argument is a float. The code above will break if you pass in floating point numbers because sign will return -1.0, 0.0, or 1.0. But if you replace sign(x-y) with int(sign(x-y)) it will work for floating point arguments.
Related post: Symbol pronunciation
The post Spaceship operator in Python first appeared on John D. Cook.