1

Could someone explain me why in for in l5 loop I got 2 True values, but from l5.count(True) I got only 1?? And why l5.count(not 0) returns only 1?

I know about other ways to get what I need: filter + lambda or sum + for + if, but I try understand it :)

Under part from Python console I've asked.

Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 '''

l5 = [0, 0, 0, 1, 2]
l5.count(True)
Out[3]: 1
for x in l5:
    print(x, bool(x))
    
0 False
0 False
0 False
1 True
2 True
l5.count(0)
Out[5]: 3
l5.count(not 0)
Out[6]: 1
l5.count(not False)
Out[7]: 1

'''

3
  • count(True) will list only 1 value because there is only "1"(True) in the list. But bool(x) will return 1 for every non-zero value of x. That is why you have 2 true(s). Commented Mar 11, 2021 at 13:31
  • 1
    Just because you can call bool on the items in the list and the result is True or False doesn't mean the list actually contains these booleans. Commented Mar 11, 2021 at 13:44
  • It was not clear for me, but now I understand what happened with that '2' in my list. Thanks guys for Ur help. Commented Mar 11, 2021 at 20:15

1 Answer 1

1

False in python is numerically equal to 0 and True is numerically equal to 1.

and so not False will be equal to True which will be numerically equal to 1

l5 = [0, 0, 0, 1, 2]
l5.count(True) # is equivalent to l5.count(1)
Out[3]: 1
l5.count(not 0) # is equivalent to l5.count(1)
Out[6]: 1
l5.count(not False) # is equivalent to l5.count(1)
Out[7]: 1

Also

l5.count(False) # is equivalent to l5.count(0)
Out[8]: 3

When you do l5.count(True)

Internally python check it with each element in the list l5

0==True ?
0==True ?
0==True ?
1==True ?
2==True ?

Now as True is bool type and others are int, python does an implicit type conversion from bool to int (as to do a comparison type should be same)

So as True is numerically equivalent to 1:

Count=0

0==1 ? No
0==1 ? No
0==1 ? No
1==1 ? Yes; Count += 1 
2==1 ? No

Final output : 1

Now this was when type conversion from bool to int

In conversions from int to bool:

0 is treated as False and everything other than 0 , -1,-2,-3,... 1,2,3,.. are treated as True.

and so

>>> bool(-1)
True

>>> bool(1)
True

>>> bool(2)
True

>>> bool(0)
False

>>> not 2
False

# as 2 is equivalent to True and "not True" is False

You can read more about this here

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

Comments

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.