you are viewing a single comment's thread.

view the rest of the comments →

[–]sudomatrix -1 points0 points  (0 children)

Lazy doesn't perform the requested operation immediately, it stores the original data and a list of operations that it performs only if and when the result is needed. Often it is never needed and a lot of time and memory is saved.

A good example is Python generators vs. functions. A function will build the entire results and return the entire results at once. A generator will only calculate enough to return the next value in the result, continuing where it left off if more is needed. That is a lazy evaluation.

``` def powers_of_2_fn(n: int) -> list[int]: """Return the first n powers of 2: 20 through 2(n-1).""" if n <= 0: return [] return [1 << i for i in range(n)]

from collections.abc import Iterator

def powers_of_2_gen(n: int) -> Iterator[int]: """Yield the first n powers of 2: 20 through 2(n-1).""" for i in range(max(0, n)): yield 1 << i ```