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

The speed difference of two generators in any (built in function)

In this code, why is the second output faster than the first!?

Both do almost the same thing and have the same result.


from timeit import timeit

lst = [0] * 10000000

txt1 = "any(i % 2 for i in lst)"
txt2 = "any(True for i in lst if i % 2)"

print(timeit(txt1, globals=globals(), number=2))
print(timeit(txt2, globals=globals(), number=2))

result:

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

Time : 2.112963530991692
Time : 0.9412867689970881

>Solution :

like @sj95126 said in the comments: the first produces 10000000 values for any() to check, the second generator produces 0 values

you can check it by calling list on it instead of any, in a more smaller sample of course

>>> lst = [0]*10
>>> any(i % 2 for i in lst)
False
>>> list(i % 2 for i in lst)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> any(True for i in lst if i % 2)
False
>>> list(True for i in lst if i % 2)
[]
>>> 
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