![]() |
Error in the method "count" for tuple - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Error in the method "count" for tuple (/thread-43580.html) |
Error in the method "count" for tuple - fff - Nov-23-2024 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. RE: Error in the method "count" for tuple - DeaD_EyE - Nov-23-2024 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]: 2A 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 RE: Error in the method "count" for tuple - fff - Nov-24-2024 Thank you for your detailed response. |