Is there any difference between:
if any([value % 2 for value in values]):
print('done')
and
if any(value % 2 for value in values):
print('done')
where values is an array of 0-20?
I know that any()
checks to see if any value in the array meets the requirement, but want to know if there is any difference between the functions.
CodePudding user response:
The first one computes the entire list first, and then apply any
. The second one, on the other hand, is "lazy"; if some element is truthy, any
returns True
immediatly, without going further.
def foo(x):
print(f"foo({x}) is called!")
return x >= 5
print(any([foo(x) for x in range(10)]))
# foo(0) is called!
# foo(1) is called!
# foo(2) is called!
# foo(3) is called!
# foo(4) is called!
# foo(5) is called!
# foo(6) is called!
# foo(7) is called!
# foo(8) is called!
# foo(9) is called!
# True
print(any(foo(x) for x in range(10)))
# foo(0) is called!
# foo(1) is called!
# foo(2) is called!
# foo(3) is called!
# foo(4) is called!
# foo(5) is called!
# True
As you can see, the second one does not evaluate foo(x)
for x > 5
, since any
has already found foo(5) == True
, which is enough to say the result is True
.
CodePudding user response:
The difference between the two are that the first constructs a temporary list from as long as values
and then passes it on to any()
(and then deletes it). The second is using what is called a generator expression which will iteratively calculate and yield as needed and passed them on to any()
. Because of the way any()
works, it may stop doing this before reaching the end because the condition has been satisfied. For very large datasets the latter will require significantly less memory to complete (and potentially less processor time if it stops "early").