Table of Contents
Introduction
Python built-in functions any() and all() are equivalent to series of “and” and “or “ operators of Python. The functions short-circuit the execution.
ANY() function iterates over the values provided and returns TRUE as soon as the first TRUE value is discovered. If all the values provided are FALSE or is empty, FALSE is returned. It acts as the sequence of OR operation on provided values.
ALL() function iterates over all the values provided and return TRUE if all the values are TRUE else if any of the value is FALSE, FALSE is returned. It acts as the sequence of AND operation over the provided values.
Syntax
Syntax of any: any(iterables)
Syntax of all: all(iterables)
Program
Example 1
# Short-circuit at third value as it is True, hence returns True print (any([False, False, True, False])) # All values are False, hence returns False print (any([False, False, False, False])) # Short-circuit at first value as it is True, hence returns True print (any([True, False, False, False]))
Output:
True
False
True
Example 2
# Short-circuit at first value as it is False, hence returns False print (all([False, False, True, False])) # All values are False, hence returns False print (all([False, False, False, False])) # Short-circuit at second value as it is False, hence returns False print (all([True, False, False, False])) # All values are True, hence returns True print (all([True, True, True, True])) # No value passed, hence returns True print (all([ ]))
Output:
False
False
False
True
True
Example 3
flist=[] slist=[] # All numbers are in form: 4*num-2 for num in range(1,51): flist.append(4*num-2) # stores even number for num in range(0,50): slist.append(flist[num]%2==0) print('Are all numbers in first list are even?') print(all(slist))
Output:
Are all numbers in first list are even?
True
0 Comments