0

I am using the all function where I am evaluate if one item in the list would make the entire list false. Where I am confused is the first print statement returns false which is correct but the second returns True which is incorrect to my understanding. If all in the list are 0's then they both report true. I don't understand why the second print outputs true when the list does not equal 0, because the last element is 1.

list_1 = [0,0,0,1]
print(all(ele == 0 for ele in list_1))
print(all(list_1) == 0)
newdeveloper
  • 534
  • 3
  • 17

1 Answers1

0

In the second instruction, all(list_1) is returning False.

This is false-like, as is 0, so when you test whether all(list_1) == 0, the answer is True.

print( all([1, 0, 1]) ) # -->  False
print( False == 0 )   # -->  True

Remember that in Python, False does == 0

What is not so obvious, perhaps, is that in Python, the equality test considers False to be equal to 0. If you think it incorrect, here is the evidence:

enter image description here

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
  • The second instruction `print(all(list_1) == 0)` returns `True` not `False`. If i would set `list_1=[0,0,0,0]` then both statements would return `True`. Because both would evaluate to 0. However with the list `list_1=[0,0,01]` the first returns false which is correct but the second returns `True` which is incorrect. Because the expression does not equal 0. – newdeveloper Mar 21 '23 at 19:05
  • @newdeveloper How is it not correct? You don't understand it maybe, but it does exactly what it's supposed to... [`all(list_1)`](https://docs.python.org/3/library/functions.html#all) will return `False` as long as there is at least one `0`. `False` is equal to `0` while `True` is equal to `1`. When `all(list_1)` returns `False` and you check if it's `== 0` - that returns `True`. That is ***not*** the way to check if all elements of a list are `0`. The first line of code does that – Tomerikoo Mar 22 '23 at 09:04