參考答案
What is any()
?
any()
is a function that takes in an iterable (such as a list, tuple, set, etc.) and returns True
if any of the elements evaluate to True
, but it returns False
if all elements evaluate to False
.
Passing an iterable to any()
to check if any of the elements are True
can be done like this:
one_truth = [True, False, False]
three_lies = [0, '', None]
print(any(one_truth))
print(any(three_lies))
Output:
True
False
The first print statement prints True
because one of the elements in one_truth
is True
.
On the other hand, the second print statement prints False
because none of the elements are True
, i.e., all elements are False
.
Use
any()
when you need to check a long series ofor
conditions.
What is all()
?
all()
is another Python function that takes in an iterable and returns True
if all of the elements evaluate to True
, but returns False
if otherwise.
Similar to any()
, all()
takes in a list, tuple, set, or any iterable, like so:
all_true = [True, 1, 'a', object()]
one_true = [True, False, False, 0]
all_false = [None, '', False, 0]
print(all(all_true))
print(all(one_true))
print(all(all_false))
Output:
True
False
False
The first function call returned True
because all_true
was filled with truthy values.
Passing one_true
to all()
returned False
because the list contained one or more falsy values.
Finally, passing all_false
to all()
returns False
because it also contained one or more falsy values.
Use
all()
when you need to check a long series ofand
conditions.