Generator Expressions As Lazy Pipelines

Chain generator expressions so large inputs stream through the pipeline one element at a time, with no intermediate lists.

PythonData Integrity

Code

pythonsnippet
22 lines
def main() -> None:
    # 大输入:边读边处理,内存占用与规模解耦
    numbers = range(1, 1_000_001)

    # 三步管道全部惰性:推导式不带括号才是生成器
    squares = (n * n for n in numbers)
    evens = (s for s in squares if s % 2 == 0)
    limited = (s for i, s in enumerate(evens) if i < 5)

    print(list(limited))

    # 对照:列表推导会一次性物化 100 万个元素
    first_five = [n * n for n in range(1, 11) if (n * n) % 2 == 0][:5]
    print(first_five)

    # any/all 短路消费:命中即停,不跑完整个序列
    has_big = any(n > 999_998 for n in numbers)
    print('has big:', has_big)


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

[4, 16, 36, 64, 100]
[4, 16, 36, 64, 100]
has big: True

How it works

Generator Expressions As Lazy Pipelines comes down to the function main.

Applying it

Signature: def main() -> None

Running the file prints labeled results such as has big: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

What does Generator Expressions As Lazy Pipelines print when run?
The script runs standalone; its 1 labeled outputs include `has big:`.