all() always returns True unless there is an element in the sequence that is False.
Your loop produces 0 items, so True is returned.
This is documented:
Return
Trueif all elements of the iterable are true (or if the iterable is empty).
Emphasis mine.
Similarly, any() will always return False, unless an element in the sequence is True, so for empty sequences, any() returns the default:
>>> any(True for _ in '')
False
Answer from Martijn Pieters on Stack Overflowall() always returns True unless there is an element in the sequence that is False.
Your loop produces 0 items, so True is returned.
This is documented:
Return
Trueif all elements of the iterable are true (or if the iterable is empty).
Emphasis mine.
Similarly, any() will always return False, unless an element in the sequence is True, so for empty sequences, any() returns the default:
>>> any(True for _ in '')
False
As the documentation states, what all does is:
Return True if all elements of the iterable are true (or if the iterable is empty).
Videos
Suppose you have a list of numbers, and you want to check if any of the numbers are greater than a certain value, or if all of the numbers are less than a certain value.
That can be done with this simple code:
# Original list lst = [1, 2, 3, 4, 5] # Check if any number is greater than 3 has_greater_than_3 = any(x > 3 for x in lst) # Check if all numbers are less than 5 all_less_than_5 = all(x < 5 for x in lst) # Print the results print(has_greater_than_3) # True print(all_less_than_5) # False
The 'any' function returns True if at least one element meets the condition, and the 'all' function returns True if all elements meet the condition.
The best answer here is to use all(), which is the builtin for this situation. We combine this with a generator expression to produce the result you want cleanly and efficiently. For example:
>>> items = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
True
>>> items = [[1, 2, 0], [1, 2, 1], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
False
Note that all(flag == 0 for (_, _, flag) in items) is directly equivalent to all(item[2] == 0 for item in items), it's just a little nicer to read in this case.
And, for the filter example, a list comprehension (of course, you could use a generator expression where appropriate):
>>> [x for x in items if x[2] == 0]
[[1, 2, 0], [1, 2, 0]]
If you want to check at least one element is 0, the better option is to use any() which is more readable:
>>> any(flag == 0 for (_, _, flag) in items)
True
If you want to check if any item in the list violates a condition use all:
if all([x[2] == 0 for x in lista]):
# Will run if all elements in the list has x[2] = 0 (use not to invert if necessary)
To remove all elements not matching, use filter
# Will remove all elements where x[2] is 0
listb = filter(lambda x: x[2] != 0, listb)