7
[1, 1, 1, 2, 2, 3].count(True)

>>> 3

Why does this return 3 instead of 6, if bool(i) returns True for all values i not equal to 0?

2 Answers 2

3
In [33]: True == 1
Out[33]: True

In [34]: True == 2
Out[34]: False

In [35]: True == 3
Out[35]: False

True and False are instances of bool, and bool is a subclass of int.

From the docs:

[Booleans] represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

Sign up to request clarification or add additional context in comments.

Comments

2

This is better done with a comprehension:

>>> sum(1 for i in [1,1,1,2,2,3,0] if i)
6

or

sum(bool(i) for i in [1,1,1,2,2,3,0])

Or count the opposite way, since there is no ambiguity about False is something other than 0

>>> li=[1, 1, 1, 2, 2, 3, 0]
>>> len(li) - li.count(False)
6

Better still:

sum(map(bool,li))

5 Comments

I should have clarified that it wasn't code I was actually intending to use--I was just experimenting with the interpreter, finding edge cases and such.
No, no, I appreciate the input. The more I can learn, the better.
Don't do comparisons of '== True' or '!= True', just treat the values as booleans: sum(1 for i in seq if i), or simpler, sum(bool(i) for i in seq), or simplest sum(map(bool,seq)).
Here's a surprise: sum(not not i for i in seq) is twice as fast as sum(bool(i) for i in seq) (using timeit module).
Function calls are very expensive in Python... While you are timing, what about map(bool,li)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.