Content · Programming · Python

Python itertools.chain.from_iterable() Method: Usage and Examples

Flatten one level of an iterable containing other iterables.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Flatten one level of an iterable containing other iterables.

What You Will Learn


chain.from_iterable(groups) accepts a single iterable of iterables, useful when batches are generated dynamically. It does not recursively flatten arbitrary nesting.

Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from itertools import chain
print(list(chain.from_iterable([[1, 2], [], [3, 4]])))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: itertools.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

For the chosen input, the expression list(chain.from_iterable([[1, 2], [], [3, 4]])) prints [1, 2, 3, 4]. Compare that result with the rule above before you change the argument.

Expected output from the example:

[1, 2, 3, 4]

When You Would Use This


This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.

Practice: Modify the Code


Flatten batches of invoice numbers.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Passing an ordinary string and expecting complete strings rather than characters.
  • Overlooking this documented constraint: it does not recursively flatten arbitrary nesting.

Key Takeaways


  • Flatten one level of an iterable containing other iterables.
  • chain.from_iterable(groups) accepts a single iterable of iterables, useful when batches are generated dynamically.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.