Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Question about difference between two expressions

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading