InterviewSolution
| 1. |
Explain built-in any() and all() functions. |
|
Answer» These two built-in functions EXECUTE logical or / and operators successively on each of the items in an iterable such as list, tuple or string. The all() FUNCTION returns True only if all items in the iterable return true. For empty iterable, all() function returns true. Another feature of all() function is that the evaluation stops at the first instance of returning false, abandoning the REMAINING items in the sequence. On the other hand any() function returns True even if one item in the sequence returns true. Consequently, any() function returns false only if all items evaluate to false (or it is empty). To check the behaviour of these functions, let us DEFINE a lambda function and subject each item in the list to it. The lambda function itself returns true if the number argument is even. >>> iseven=lambda X:x%2==0 >>> iseven(100) True >>> iseven(101) False >>> lst=[50,32,45,90,60] >>> all(iseven(x) for x in lst) False >>> any(iseven(x) for x in lst) True |
|