C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
So: Any() requires at least one element that does not evaluate to False. Zero evaluates to False.
Python program that uses any
# Test any with all zero elements.
# ... These evaluate to false.
values = [0, 0, 0]
result = any(values)
print("ANY", values, result)
# Test any with a 1 element.
# ... This element evaluates to true, so any is true.
values = [0, 0, 1]
result = any(values)
print("ANY", values, result)
Output
ANY [0, 0, 0] False
ANY [0, 0, 1] True
Any: The any function will return False on this list. No element in the list is True.
Python program that uses any, many false elements
# These elements all evaluate to false.
# ... None, empty arrays, empty strings, and 0 are false.
# ... So any is false.
values = [None, [], "", 0]
result = any(values)
print(result)
Output
False
Python program that compares any to all
values = [0, None, "cat"]
# Test any() and all() functions on this list.
# ... One "true" element means any is true.
# ... But all() is false because there are 2 false elements.
print("ANY", values, any(values))
print("ALL", values, all(values))
Output
ANY [0, None, 'cat'] True
ALL [0, None, 'cat'] False
Python program that tests empty list
# This is an empty list.
# ... Any returns false.
empty = []
result = any(empty)
print(result)
Output
False
Version 1: This version of the code uses the any() method on a list. It ensures any() does not return False.
Version 2: Here we use a nested for-loop to implement the same logic that any() uses. The source code is somewhat longer.
Result: In PyPy the for-loop is faster than any. Perhaps the compiler can optimize a nested loop faster than an any call.
Python program that benchmarks any, for-loop
import time
values = [0, None, 100]
print(time.time())
# Version 1: use any() function.
i = 0
while i < 10000000:
v = any(values)
if v == False:
break
i += 1
print(time.time())
# Version 2: implement any logic with for-loop.
i = 0
while i < 10000000:
t = False
for v in values:
if v:
t = True
break
if t == False:
break
i += 1
print(time.time())
Output
1453910914.887
1453910915.356 Version 1, any() = 0.46899986267 s
1453910915.528 Version 2, for, if = 0.17200016975 s