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

For loop evaluation order

I was looking into the all and any functions to see their guarantees about order.

For example, the documentation states that the any function is equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

However, when running the following code:

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

a = 1
any([a == 1, a[1] == 1])

I would expect the second expression to not be evaluated and, thus, would return True. Instead, the second line throws TypeError: 'int' object is not subscriptable. I initially believed that this was some inconsistency in the documentation but, indeed, when running with the for loop version, the result is the same.

My question is, how does it throw the exception, if it should not evaluate the second expression by returning True early? I thought that python only checked those errors when running the expressions.

Changing to

a = 1
any([a == 1, print('hello world')])

Also evaluates the print in both versions. Can anyone shine some light on this? Thanks in advance.

Note: using python 3.8.10 and interaction was performed in the python shell.

>Solution :

As @Barmar said, all the elements inside of the list must be evaluated when the list is created, to create something similar to that but lazy you could do:

def it():
    yield print(1)
    yield print(2)
    yield True
    yield print(3)
    
print(any(it()))

With output:

1
2
True
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