I am write a function that can return Boolean if every string in a list contains the word 'red'. Below is the code that I came up with, it worked well for test case AllRed(["red hat", "a pair of red shoes", "three red apples"]); and test case AllRed(["red hat", "white shirt", "black eyes"]). However, when I tested it with an empty list, it returned True.
def AllRed (lst):
return all("red" in i for i in lst)
AllRed([])
It is supposed to return false for empty list.
CodePudding user response:
The all()
function is required to return True
for empty lists. This ensures that the following equivalence will always be true:
all(list1) and all(list2) == all(list1 list2)
When list1
is empty, list1 list2
is the same as list2
. So we need all(list1)
to return True
.
Similarly, any()
returns False
for an empty list, so that
any(list1) or any(list2) == any(list1 list2)
is true.
CodePudding user response:
It is because when your iterable (lst
) is empty, there is nothing to iterate over; and if you see how all()
works, it returns True
when iterable is empty.
See how all()
works