Search code examples
pythonlistcomparison-operators

Please explain (python): example_list[a < b]


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

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: