The itertools is a module in Python having a collection of functions for handling iterators. They make iterating through the iterables like lists and strings very easily.

itertools.chain() is a function in itertools module that takes a series of iterables and returns one iterable. It basically groups all the iterable together and produces a single iterable as output. They come under the category of terminating iterators.

Syntax

itertools.chain(*iterables)

Example 1

Lets take an example to understand its functioning.

from itertools import chain
# list of odd numbers
odd = [1, 3, 5, 7, 9]
# list of even numbers
even = [2, 4, 6, 8, 10]

# chaining odd and even numbers 
numbers = list(chain(odd,even))

print(numbers)

Output

[1 2 3 4 5 6 7 8 9 10]

Example 2

Combining two lists of alphabets and sorting them.

from itertools import chain

# some vowels
vowels = ['a', 'e', 'i', 'o', 'u']
# some consonants
consonants = ['b', 'c', 'd', 'f']

# combined list
combine = list(chain(consonants, vowels))

combine.sort()

print(combine)

Output

['a', 'b', 'c', 'd', 'e', 'f', 'i', 'o', 'u']

Example 3

from itertools import chain
 
res = list(chain('ABC', 'DEF', 'GHI', 'JKL'))
 
print(res)

Output

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']

Example 4

Now consider the given list : li =['123', '456', '789'] You are supposed to calculate the sum of the list taking every single digit into account. So the answer should be : 1+2+3+5+6+7+8+9 = 45 This can be achieved easily using the code below :

from itertools import chain
 
li = ['123', '456', '789']
 
res = list(map(int, list(chain.from_iterable(li))))
 
sum_of_li = sum(res)
 
print("res =", res, end ="\n\n")
print("sum =", sum_of_li)

Output

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

sum = 45

One more popular function from itertools module is itertools.product, which I will be discussing in the next blog.

NOTE : These are just my notes, some of the texts can be similar to what you see in GFGs articles. I’ve tried not to be unnecessarily creative with my words.