3

Can someone explain this syntax to me? I've searched through docs/blogs but can't find any mention of using booleans as indices for array slicing. I found this syntax in this script convert_base.py:

is_negative = num_as_string[0] == '-'
num_as_string[is_negative:]

My guess is that False is being cast to 0 and True is being cast to 1. Does anybody know for sure or can point me to any 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]
martineau
  • 119,623
  • 25
  • 170
  • 301
Andrew Toy
  • 93
  • 1
  • 5
  • It's best not to think in terms of "casting" in Python. While the term is often thrown around loosely, it's pretty meaningless in a very dynamic language like Python where everything is an object. – juanpa.arrivillaga Apr 18 '17 at 21:37

2 Answers2

4

Apart from the fact that True and False are subclasses of int which are easily coerced to 1 and 0 respectively, their __index__ methods used by the Python slice mechanism returns 1 and 0:

>>> True.__index__()
1
>>> False.__index__()
0

You can generally slice with arbitrary objects by defining an __index__ method:

>>> 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]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2

True and False are instances of bool, a subclass of int. True has the integer value 1, False has the integer value 0.

timgeb
  • 76,762
  • 20
  • 123
  • 145