Python all() function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Python all() function

Why this statement return false? lst = [5,5,5,5,5] x = all(lst) == 5 print(x)

1st Apr 2024, 5:52 AM
Oliver Pasaribu
8 Answers
+ 4
Oliver Pasaribu , to check if all values of a list follow a certain condition, we can use all() with a list comprehension: lst = [5,5,5,5,5] x = all(num == 5 for num in lst) # result is True lst = [5,5,5,5,3,5] x = all(num == 5 for num in lst) # result is False
1st Apr 2024, 6:19 AM
Lothar
Lothar - avatar
+ 2
The all() function checks that every element of an iterable has a "truthy" value. 5 is truthy, so the all() function returns True. But True is not equal to 5.
1st Apr 2024, 6:06 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Oliver Pasaribu there is no reason why a different Python interpreter should give a different answer to the SAME code. it should not. Maybe the code was different. Can you show a screenshot and specifically which interpreter you tried?
1st Apr 2024, 6:36 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Oliver Pasaribu , reference for all() https://docs.python.org/3/library/functions.html#all and for its companion, any() https://docs.python.org/3/library/functions.html#any
1st Apr 2024, 11:36 PM
Rain
Rain - avatar
+ 1
The statement returns False because all(lst) evaluates to True since all elements in the list lst are truthy (non-zero). However, True is not equal to 5, so x becomes False. Therefore, the result of the statement print(x) is False.
2nd Apr 2024, 11:12 AM
Vivienne Medrano
0
I use other python interpreter and it return True. So in this identical case, sololearn python interpreter must return True too. What do you think Tibor Santa?
1st Apr 2024, 6:15 AM
Oliver Pasaribu
0
This problem has a common with assertion in c++ or Java may be?
1st Apr 2024, 6:21 AM
Oliver Pasaribu
0
No, this is like an assertion mechanism. It convince that all i in list store int value 5.
2nd Apr 2024, 10:37 PM
Oliver Pasaribu