Is any() evaluated lazily?

前端 未结 7 536
别跟我提以往
别跟我提以往 2021-01-18 03:59

I am writing a script in which i have to test numbers against a number of conditions. If any of the conditions are met i want to return True an

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-18 04:27

    While the all() and any() functions short-circuit on the first "true" element of an iterable, the iterable itself may be constructed in a non-lazy way. Consider this example:

    >> any(x == 100 for x in range(10**8))
    True
    

    This will take several seconds to execute in Python 2 as range(10**8) constructs a list of 10**8 elements. The same expression runs instantly in Python 3, where range() is lazy.

提交回复
热议问题