Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

itertools.chain

Yields the members of each input iterable to form one consecutive sequence.

Version: Python 3.14; repository image, production runtime not attested

Syntax

itertools.chain(*iterables)
itertools.chain.from_iterable(iterable)

Yields the members of each input iterable to form one consecutive sequence.

An empty input contributes nothing. Flattening nested iterables removes just one level.

chain takes its sources as separate positional arguments and exhausts each in turn: [1, 2], an empty list and (3,) yield 1, 2, 3. The class method instead reads sources from one outer iterable. For strings ab and c, iterating one level yields a, b, c.

import itertools as I
assert list(I.chain([1], [], [2])) == [1, 2]
assert list(I.chain.from_iterable([[[1]], [[2]]])) == [[1], [2]]

Examples

import itertools as I
print(list(I.chain([1, 2], [], (3,))))
print(list(I.chain.from_iterable(["ab", "c"])))

Result

[1, 2, 3]
['a', 'b', 'c']

chain takes its sources as separate positional arguments and exhausts each in turn: [1, 2], an empty list and (3,) yield 1, 2, 3. The class method instead reads sources from one outer iterable. For strings ab and c, iterating one level yields a, b, c.

Sources