Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 [1]: X = rand(10)

In [2]: large = X>0.6

In [3]: large.dtype
Out[3]: dtype('bool')

In [4]: large.sum()
Out[4]: 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.

share|improve this question
In some languages "true" is -1 – JBRWilkinson Oct 20 '12 at 9:57
up vote 6 down vote accepted

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:

.__bool__() evaluates to False, 

and everything else is True.

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

>>> int(True)
>>> int(False)
>>> True + True

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.