if any([x % 2 for x in result]):
print("good")
and
if any(x % 2 for x in result):
print("good")
I’m studying Python, but not sure what is difference between two expressions shown above.
Does the first expression check each element in list?
I try to code myself, to solve this problem, but I don’t get it why those two expressions are different and what they do.
>Solution :
To see what’s going on, let’s run the following program:
def test(i):
print(i)
if i == 5:
return True
return False
if any([test(i) for i in range(10)]):
print("Done")
if any(test(i) for i in range(10)):
print("Done")
0
1
2
3
4
5
6
7
8
9
Done
0
1
2
3
4
5
Done
The first version creates a list using list comprehension, and after the entire list is created, it is then checked for True/False values. You can see the entire list being created, because all numbers up to 10 are printed.
However, in the second version, you’ll see that the output only goes up to 5. This is because the second creates a generator expression, which the any function than evaluates one-by-one. For example, as soon as i == 5, the any function returns true and stops iterating the generator.
Let’s replicate the any function in the same way it works in the second if-statement.
def any(gen):
for i in gen:
if i:
return True
return False
This is pretty similar to how the builtin any function works. It looks at each element, checks if it is True, and prematurely returns if a True value is found. The reason generator expressions are more efficient is because values are being created one-by-one, rather than all at once with the list comprehension.