Is any() evaluated lazily?

前端 未结 7 484
别跟我提以往
别跟我提以往 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:25

    As Tim correctly mentioned, any and all do short-circuit, but in your code, what makes it lazy is the use of generators. For example, the following code would not be lazy:

    print(any([slow_operation(x) for x in big_list]))
    

    The list would be fully constructed and calculated, and only then passed as an argument to any.

    Generators, on the other hand, are iterables that calculate each item on demand. They can be expressions, functions, or sometimes manually implemented as lazy iterators.

提交回复
热议问题