Partitioning an array with boolean indices
Can someone explain this syntax to me? I've searched in docs / blogs but can't find any mention of how to use booleans as indices to slice an array. I found this syntax in this script convert_base.py
:
is_negative = num_as_string[0] == '-'
num_as_string[is_negative:]
I am assuming False is dropped to 0 and True is dropped to 1. Does anyone know for sure or can point me to some documentation?
>>> a = [1,2,3]
>>> a[True:]
[2,3]
>>> a[False:]
[1,2,3]
>>> a[:False]
[]
>>> a[:True]
[1]
>>> a[False:True]
[1]
>>> a[True:True]
[]
>>> a[False:False]
[]
>>> a[True:False]
[]
>>> a[False::True+1]
[1,3]
source to share
In addition to that True
and False
are subclasses int, which are easily forced to 1 and 0 respectively, their methods __index__
used Python cutoff mechanism is returned 1
and 0
:
>>> True.__index__()
1
>>> False.__index__()
0
You can usually trim arbitrary objects by specifying a method __index__
:
>>> class Decade(object):
... def __index__(self):
... return 10
...
>>> range(20)[Decade():] # list(range(...))[Decade():] for Python 3
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
source to share