ZetCode

Python chain

last modified November 30, 2026 Python 3.15

In this article we show how to join iterables with the itertools.chain function.

The chain function takes any number of iterables and returns a single iterator. The iterator first produces all items of the first iterable, then all items of the second one, and so on. It does not copy the items into a new list; it reads them from the original iterables one at a time, only when they are requested. The variant chain.from_iterable takes the iterables from a single iterable, which makes it the standard tool for flattening a list of lists.

Joining two lists

In the simplest case, chain lets us loop over two lists as if they were one.

two_lists.py
from itertools import chain

morning = ['coffee', 'news', 'email']
evening = ['dinner', 'book']

for activity in chain(morning, evening):
    print(activity)

The for loop goes through the morning activities and then continues with the evening ones. Neither list is modified, and no third list is created.

$ python two_lists.py
coffee
news
email
dinner
book

Different types of iterables

The arguments of chain do not have to be of the same type. Any iterable works: strings, tuples, dictionaries, ranges, files, or other iterators.

mixed_types.py
from itertools import chain

word = 'sky'
nums = (1, 2, 3)
capitals = {'sk': 'Bratislava', 'cz': 'Prague'}
evens = range(0, 8, 2)

print(list(chain(word, nums, capitals, evens)))
print(list(chain(capitals.values(), capitals.items())))

Each argument is iterated in its usual way. A string produces its characters and a dictionary produces its keys. To get the values or the key-value pairs, we pass the values or items views, as in the second call.

$ python mixed_types.py
['s', 'k', 'y', 1, 2, 3, 'sk', 'cz', 0, 2, 4, 6]
['Bratislava', 'Prague', ('sk', 'Bratislava'), ('cz', 'Prague')]

chain versus the + operator

The + operator also joins sequences, but it works differently. It builds a new object right away, and both operands must be of the same type.

plus_vs_chain.py
from itertools import chain

a = [1, 2, 3]
b = (4, 5)

print(a + list(b))

c = chain(a, b)
a.append(10)

print(list(c))

print(a + b)

To add a tuple to a list with +, we must convert it first. The chain object does not copy anything when it is created. It reads from a only when we consume it, so it sees the value appended in the meantime. The last line shows that a list and a tuple cannot be joined with +.

$ python plus_vs_chain.py
[1, 2, 3, 4, 5]
[1, 2, 3, 10, 4, 5]
Traceback (most recent call last):
  File "/home/user/python/plus_vs_chain.py", line 13, in <module>
    print(a + b)
          ~~^~~
TypeError: can only concatenate list (not "tuple") to list

A chain is used only once

The chain function returns an iterator, not a sequence. Like every iterator, it can be consumed only once.

one_shot.py
from itertools import chain

c = chain([1, 2], [3, 4])

print(next(c))
print(list(c))
print(list(c))

The next call takes the first item, so the first list call gets only the remaining three items. The second list call gets nothing, because the iterator is exhausted. If we need to go through the items again, we either call chain again or store the result in a list.

$ python one_shot.py
1
[2, 3, 4]
[]

chain is lazy

The chain object does not touch an iterable until it needs its items. This is visible when the inputs are generators that print what they do.

lazy_chain.py
from itertools import chain


def read_batch(name, values):
    print(f'opening {name}')
    for v in values:
        yield v
    print(f'closing {name}')


c = chain(read_batch('A', [1, 2]), read_batch('B', [3, 4]))
print('chain created')

print(next(c))
print('---')

for v in c:
    print(v)

Creating the chain runs no generator code. The first next call starts generator A and takes one value from it. Generator B is started only after A is finished. If we stopped after the first item, B would never run. How generators pause and resume is explained in Python generators.

$ python lazy_chain.py
chain created
opening A
1
---
2
closing A
opening B
3
4
closing B

Flattening a list of lists

When the iterables are stored in a list, we can unpack the list into the arguments of chain with the star operator, or we can use chain.from_iterable.

unpack_lists.py
from itertools import chain

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

print(list(chain(*matrix)))
print(list(chain.from_iterable(matrix)))

print(sum(chain.from_iterable(matrix)))

Both calls flatten the matrix by one level and give the same result. The from_iterable form is preferred: it takes the list as it is, so the outer list is not unpacked into a tuple of arguments. The last line shows that the chained items can go straight into a function such as sum, without building a flat list first.

$ python unpack_lists.py
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
45

A lazy outer iterable

The difference between the two forms matters when the outer iterable is itself lazy. Unpacking with the star operator reads the whole outer iterable before chain starts. The from_iterable method reads it one item at a time.

lazy_outer.py
from itertools import chain, islice


def pages():
    n = 1
    while True:
        print(f'fetching page {n}')
        yield [f'{n}a', f'{n}b', f'{n}c']
        n += 1


items = chain.from_iterable(pages())

print(list(islice(items, 5)))

The pages generator simulates an endless paged result, for example from a web service. The chain.from_iterable method fetches a new page only when the previous one is used up, so two pages are enough to get five items. Writing chain(*pages()) here would try to fetch all pages before producing a single item and the program would never finish.

$ python lazy_outer.py
fetching page 1
fetching page 2
['1a', '1b', '1c', '2a', '2b']

Flattening only one level

The chain.from_iterable method removes only one level of nesting. Deeper structures need a recursive function.

one_level.py
from itertools import chain

data = [[1, 2], [3, [4, [5, 6]]], 7, 'ab']


def flatten(items):
    for item in items:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item


print(list(chain.from_iterable([[1, 2], [3, [4, 5]]])))
print(list(flatten(data)))

The first call leaves the inner list [4, 5] unchanged. The recursive flatten generator descends into every list with yield from. It checks for lists explicitly, because a generic check for iterables would also split the string 'ab' into characters, and a string of length one would recurse forever.

$ python one_level.py
[1, 2, 3, [4, 5]]
[1, 2, 3, 4, 5, 6, 7, 'ab']

Adding a header and a footer

Single values can be added to a chain by wrapping them in a list. This is a simple way to put a header before and a footer after a sequence of rows.

report.py
from itertools import chain

header = ['name,qty']
rows = ['apples,12', 'pears,7', 'plums,30']
footer = ['total,49']

for line in chain(header, rows, footer):
    print(line)

The header and the footer are one-item lists. The rows are not copied; the chain prints them directly from the rows list.

$ python report.py
name,qty
apples,12
pears,7
plums,30
total,49

Reading several files

A file object is an iterable of lines, so chain can join several files into one stream of lines.

two_files.py
from itertools import chain

with open('january.txt') as f1, open('february.txt') as f2:

    for n, line in enumerate(chain(f1, f2), 1):
        print(n, line.rstrip())

The january.txt and february.txt files each contain two lines of a log. The with statement opens both files and closes them at the end. The chained lines are numbered with enumerate, so the numbering continues across the file boundary. For many files, the fileinput module offers the same idea with file names and line numbers built in.

$ python two_files.py
1 2026-01-04 backup done
2 2026-01-18 disk replaced
3 2026-02-02 backup done
4 2026-02-21 power outage

Padding with repeat

A finite iterable can be followed by an infinite one. The infinite part then supplies values after the finite part is used up.

padding.py
from itertools import chain, islice, repeat

rows = [['Peter', 'Bratislava', 'IT'], ['Jana', 'Kosice'], ['Ivan']]

for row in rows:

    padded = islice(chain(row, repeat('-')), 3)
    print(' | '.join(padded))

Each row is extended with an endless supply of dashes, and islice takes exactly three fields. Rows with missing fields get padded, and complete rows are left as they are. The repeat function is covered in Python infinite iterators.

$ python padding.py
Peter | Bratislava | IT
Jana | Kosice | -
Ivan | - | -

Comparing ways to flatten

There are several ways to flatten a list of lists. In this example we compare their speed with the timeit module.

flatten_speed.py
import timeit
from itertools import chain

lists = [[i, i + 1, i + 2] for i in range(2000)]


def with_sum():
    return sum(lists, [])


def with_chain():
    return list(chain.from_iterable(lists))


def with_comprehension():
    return [x for sub in lists for x in sub]


def with_unpacking():
    return [*sub for sub in lists]


assert with_sum() == with_chain() == with_comprehension() == with_unpacking()

for fn in with_sum, with_chain, with_comprehension, with_unpacking:
    t = timeit.timeit(fn, number=200)
    print(f'{fn.__name__:20} {t:.4f} s')

The sum(lists, []) call is short but slow, because each addition creates a new, longer list; its running time grows with the square of the number of lists. The chain version and the nested comprehension are linear and close to each other. The fastest one is the comprehension with unpacking, [*sub for sub in lists], which is new in Python 3.15; see Python unpacking in comprehensions. Unlike the comprehensions, chain does not have to build a list at all, which makes it the better choice when the items are only iterated once. The timings differ from machine to machine.

$ python flatten_speed.py
with_sum             1.5176 s
with_chain           0.0124 s
with_comprehension   0.0124 s
with_unpacking       0.0073 s

Iterating over several dictionaries

In the last example we combine the items of several dictionaries. A generator expression produces the item views, and chain.from_iterable joins them into one stream of pairs.

warehouses.py
from itertools import chain

bratislava = {'chairs': 40, 'tables': 12}
kosice = {'chairs': 15, 'lamps': 30}
zilina = {'tables': 5, 'lamps': 8, 'desks': 3}

stores = [bratislava, kosice, zilina]

totals = {}

for item, qty in chain.from_iterable(s.items() for s in stores):
    totals[item] = totals.get(item, 0) + qty

print(totals)

pieces = sum(chain.from_iterable(s.values() for s in stores))
print(f'pieces in stock: {pieces}')

We have the stock of three warehouses. The loop adds up the quantities of each product across all warehouses. The second part sums all quantities into a single number. In both cases, no combined list of items is built.

$ python warehouses.py
{'chairs': 55, 'tables': 17, 'lamps': 38, 'desks': 3}
pieces in stock: 113

Source

itertools.chain, itertools.chain.from_iterable

In this article we have joined iterables with chain, compared it with the + operator, flattened lists with chain.from_iterable, and used chained iterators with generators, files, and infinite iterators. See also Python iterators, Python generators, Python lazy evaluation, and Python itertools.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.