Open In App

Python – Itertools.chain()

Last Updated : 25 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easily. One such itertools function is chain().
Note: For more information, refer to Python Itertools
 

chain() function

It is a function that takes a series of iterables and returns one iterable. It groups all the iterables together and produces a single iterable as output. Its output cannot be used directly and thus explicitly converted into iterables. This function come under the category iterators terminating iterators.
Syntax :  

chain (*iterables)

The internal working of chain can be implemented as given below :  

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

Example 1: The odd numbers and even numbers are in separate lists. Combine them to form a new single list.

Python3




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


Output: 

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

 

Example 2: Some of the consonants are in a list. The vowels are given in a list. Combine them and also sort them.

Python3




from itertools import chain
 
# some consonants
consonants = ['d', 'f', 'k', 'l', 'n', 'p']
 
# some vowels
vowels = ['a', 'e', 'i', 'o', 'u']
 
# resultatnt list
res = list(chain(consonants, vowels))
 
# sorting the list
res.sort()
 
print(res)


Output: 

['a', 'd', 'e', 'f', 'i', 'k', 'l', 'n', 'o', 'p', 'u']

 

Example 3: In the example below, Each String is considered to be an iterable and each character in it is considered to be an element in the iterator. Thus every character is yielded

Python3




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: 

Python3




from itertools import chain
 
st1 = "Geeks"
st2 = "for"
st3 = "Geeks"
 
res = list(chain(st1, st2, st3))
print("before joining :", res)
 
ans = ''.join(res)
print("After joining :", ans)


Output:
before joining : [‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’] 
After joining : GeeksforGeeks
 

chain.from_iterable() function
It is similar to chain, but it can be used to chain items from a single iterable. The difference is demonstrated in the example given below:
Example 5:

Python3




from itertools import chain
 
li = ['ABC', 'DEF', 'GHI', 'JKL']
 
# using chain-single iterable.
res1 = list(chain(li))
 
 
res2 = list(chain.from_iterable(li))
 
print("using chain :", res1, end ="\n\n")
 
print("using chain.from_iterable :", res2)


Output:
using chain : [‘ABC’, ‘DEF’, ‘GHI’, ‘JKL’]
using chain.from_iterable : [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’]
 

Example 6: Now consider a list like the one given below : 

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 :

Python3




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


Output: 

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

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

sum = 45

 

To simplify it, we combine the steps. An optimized approach is given below:

Python3




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

 



Previous Article
Next Article

Similar Reads

Python - Itertools.chain.from_iterable()
Python's Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools The functions under itertools can be classified into
2 min read
Print first n distinct permutations of string using itertools in Python
Given a string with duplicate characters allowed, print first n permutations of given string such that no permutation is repeated. Examples: Input : string = "abcab", n = 10 Output : aabbc aabcb aacbb ababc abacb abbac abbca abcab abcba acabb Input : string = "okok", n = 4 Output : kkoo koko kook okko Approach: Python provides an inbuilt method to
2 min read
Python - Itertools.tee()
In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily. One such itertools function is filterfalse(). Note: For more information, refer to Python Itertools tee() function This iterator splits the container into a number of it
2 min read
Python Itertools
Python's Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. For example, let's suppose there are two lists and you want to multiply their elements. There can be sever
13 min read
itertools.groupby() in Python
Prerequisites: Python Itertools Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Itertools.groupby() This method calculates the keys for each element prese
2 min read
Python - itertools.repeat()
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools repeat() itertools.repeat()falls under the category
2 min read
Python - Itertools.takewhile()
The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easy. One such itertools function is takewhile(). Note: For more information, refer to Python Itertools takewhile() This allows considering an item from the iterable until t
3 min read
Python - Itertools.compress()
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools Compress() The itertools.compress() falls under the
2 min read
Python - Itertools.dropwhile()
Itertools is a Python module that provide various functions that work on iterators to produce complex iterators. It makes the code faster, memory efficient and thus we see a better performance. This module is either used by themselves or in combination to form iterator algebra. Note: For more information, refer to Python Itertools Dropwhile() The d
1 min read
Python - Itertools.cycle()
Iterator is defined as object types which contains values that can be accessed or iterated using a loop. There are different iterators that come built-in with Python such as lists, sets, etc. Itertools is the Python module that contains some inbuilt functions for generating sequences using iterators. This module provides various functions that work
3 min read
Article Tags :
Practice Tags :