Python itertools.chain() Function



The Python itertools.chain() function is used to create an iterator that combines multiple iterables into a single sequence. This function is useful when you need to iterate over multiple collections sequentially as if they were a single iterable.

It takes any number of iterables as arguments and returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, and so on.

Syntax

Following is the syntax of the Python itertools.chain() function −

itertools.chain(iterable1, iterable2, ...)

Parameters

This function accepts two or more iterables as a parameter whose elements need to be combined into a single sequence.

Return Value

This function returns an iterator that yields elements from the given iterables in order.

Example 1

Following is an example of the Python itertools.chain() function. Here, we combine two lists into a single sequence −

import itertools

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = itertools.chain(list1, list2)
for item in combined:
   print(item)

Following is the output of the above code −

1
2
3
4
5
6

Example 2

Here, we chain a tuple and a list together into a single iterable using the itertools.chain() function −

import itertools

tuple1 = ("a", "b", "c")
list1 = [1, 2, 3]
combined = itertools.chain(tuple1, list1)
for item in combined:
   print(item)

Output of the above code is as follows −

a
b
c
1
2
3

Example 3

Now, we use itertools.chain() function to iterate over multiple sets in order −

import itertools

set1 = {10, 20, 30}
set2 = {40, 50, 60}
combined = itertools.chain(set1, set2)
for item in combined:
   print(item)

The result obtained is as shown below −

10
20
30
40
50
60

Example 4

The itertools.chain() function can also be used with generator expressions.

Here, we chain two generator expressions together −

import itertools

gen1 = (x for x in range(3))
gen2 = (x**2 for x in range(3, 6))
combined = itertools.chain(gen1, gen2)
for item in combined:
   print(item)

The result produced is as follows −

0
1
2
9
16
25
python_modules.htm
Advertisements