Understand itertools.chain() with Examples – Python Tutorial

By | March 28, 2023

itertools.chain() can take a series of iterables and returns one iterable. In this tutorial, we will use some examples to show you how to use it.

Syntax

itertools.chain() is defined as:

chain (*iterables)

It is equal to code below:

def chain(*iterables):
     for it in iterables:
       for each in it:
           yield each

It will take some iterables and return a one iterable.

How to use itertools.chain()?

Example 1:

import itertools
x = [[1,2, 3], [4, 5, 6]]
y = itertools.chain(x)
print(y)
for e in y:
    print(e)

Run this code, we will see:

<itertools.chain object at 0x00000133658EFB38>
[1, 2, 3]
[4, 5, 6]

Here iterables is x

Example 2:

x = [[1,2, 3], [4, 5, 6]]
x1 = [1,2,3]

y = itertools.chain(x, x1)
print(y)
for e in y:
    print(e)

Here iterables contains x and x1.

Run this code, we will see:

<itertools.chain object at 0x0000017A119BFB38>
[1, 2, 3]
[4, 5, 6]
1
2
3