# Is it correct to add booleans in order to count the number of true values in a vector?

Is it conceptually correct to sum a vector of booleans? From a mathematical point of view, I would argue it's not: `True + True != 2`. But it's quite practical to do so still! Example using the vectorised `Python` library `numpy`:

``````In : X = rand(10)

In : large = X>0.6

In : large.dtype
Out: dtype('bool')

In : large.sum()
Out: 7
``````

I don't like it, but it's very practical. Is this a good practice?

Update: the aim is to count the number of true values in a vector.\

Update 2013-02-18: I just discovered the numpy function `count_nonzero` does exactly what I need in a proper way. That means that as far as `Python` is concerned, there is no need to use the "dirty" way.

• In some languages "true" is -1 Oct 20, 2012 at 9:57

I would say it is not semantically proper to add True and True to get two. It may work, but it seems to rely on an implementation detail.

Python defines a few things as `False`, such as:

``````""
0
0.00
None,
[],
(),
.__bool__() evaluates to False,
etc...
``````

and everything else is `True`.

The `+` operator in python, when used on a `bool` will first convert it to `int`.

``````>>> int(True)
1
>>> int(False)
0
>>> True + True
2
``````

If you choose to do so in Python, make sure you comment your code accordingly.