itertools.chain Flattens One Nesting Level

chain and chain.from_iterable stream elements from several iterables lazily, flattening one nesting level without materializing intermediate lists.

PythonData Integrity

Code

pythonsnippet
19 lines
from itertools import chain

batches = [[1, 2, 3], [4, 5], [6]]

# chain(*batches) 把每个可迭代对象的元素逐个产出
print(list(chain(*batches)))

# from_iterable 不需要解包:来源是任意嵌套一层的可迭代对象
print(list(chain.from_iterable(batches)))

# 惰性:来源是生成器也按需前进,不会先物化整个列表
def stream():
    yield [10, 11]
    yield [12]

print(list(chain.from_iterable(stream())))

# 混搭类型:元组、字符串、range 串在一起
print(list(chain((7,), "ab", range(8, 10))))

Output

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

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[10, 11, 12]
[7, 'a', 'b', 8, 9]

What the code does

Count the function stream as the entire surface area of itertools.chain Flattens One Nesting Level.

Applying it

Entry signature: def stream()

Import stream from the file and call it — the rest of the code is implementation detail.

Statements that matter

def stream():
    yield [10, 11]
    yield [12]

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Every import resolves inside the standard library — `itertools`. The file defines `stream` at load time.