Question

I was reading Is there a numpy builtin to reject outliers from a list and came across a python list syntax which I am unfamiliar with.

Question: What does the the use of < or > do inside a list's []s?

e.g. example_list[a < b]

I played around in Terminal some but that didn't help me understand anything:

>>> ex = [1,2,3,4]
>>> ex[0<5]
2
>>> ex[0>5]
1
>>> ex[0>3]
1
>>> ex[0>0]
1
>>> ex[0<0]
1
>>> ex[1<0]
1
>>> ex[1<5]
2
Was it helpful?

Solution

< will return either True or False, and they are equal to 1 and 0 in Python. Hence you'll get either first or second item.

>>> True == 1
True
>>> False == 0
True
>>> 'ab'[True]
'b'
>>> 'ab'[False]
'a'

This thing was helpful in older versions of Python when the conditional expressions were not introduced:

>>> a = 'aa'
>>> b = 'bb'
>>> [10, 20][a>b]
10
>>> 20 if a > b else 10
10

Related:

OTHER TIPS

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.

They are logical calculations. It either return a 1 if the statement is True, and 0 If it is False.

Please read < as "less than". "zero is less than five" is True. In python, as many languages, True is equal to 1. The 1th item in your list is 2.

Similarly, because zero is not greater than three, and the 0th item in your list is 1, ex[0>5] gives the value 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top