That syntax works in both regular Python and in numpy, but it does different things in each place.
With regular Python numbers and containers, doing sequence[a < b]
first evaluates a < b
and gets a boolan value (True
or False
). Booleans are a subclass of integers in Python, and so they're acceptable indexes into sequences like lists and tuples. You'll sometimes see code like [1, -1][a < b]
used as shorthand for the conditional expression -1 if a < b else 1
.
In numpy code, things are a bit more complicated. If your a
and/or b
value is a numpy array, then the expression a < b
will be a boolean array with appropriate dimensions. That array can then be used as an index into another numpy array. So for instance, you can extract the values greater than 10 in an numpy array a
with a[a>10]
. This is the kind of logic that was being used in the other question you linked to.