Python Forum

Full Version: Error in the method "count" for tuple
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I just wrote this simple code to count the number of 1 in this tuple. Ironically, it returns 2 instead of 1. I have the last version of Python. Also, I checked the program with Colab, and I got the same wrong result. It is interesting that this problem occurs only for "1"!!

mixed_tuple = (1, 3.4, "ali", True, [0, 3, 3])
print(mixed_tuple.count(1))
The result will be 2.
Oh, yes and the result is right.

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

In [2]: int.mro()
Out[2]: [int, object]

In [3]: bool.mro()
Out[3]: [bool, int, object]

In [4]: ((1,)).count(1)
Out[4]: 1

In [5]: ((1, True)).count(1)
Out[5]: 2

In [6]: ((0, True)).count(1)
Out[6]: 1

In [7]: ((0, False)).count(1)
Out[7]: 0

In [8]: ((0, False)).count(0)
Out[8]: 2
A boolean is a subtype of int.
It's getting worse, if you use for keys boolean and int as keys:
In [1]: d = {0: "Foo"}

In [2]: print(d)
{0: 'Foo'}

In [3]: d[False] = "This is False"

In [4]: # now what do you expect?

In [5]: print(d)
{0: 'This is False'}
Do not mix int with bool in sequences and mappings.
Sometime the property could be easily used.

If you have a list/tuple with only boolean insde, you can sum up True, which is a subtype of int and is equal to 1.
In [1]: import random

In [2]: data = random.choices([True, False], k=10)

In [3]: print(data)
[True, False, False, False, True, False, True, True, False, True]

In [4]: # count number of True

In [5]: print(sum(data))
5
Thank you for your detailed response.