The from_iterable()
method is an alternate constructor for chain
in the itertools
module that accepts a single iterable as an argument. And all of the input iterable’s elements must also be iterable. It returns a flattened iterable with all of the input iterable’s elements.
Note: The
itertools
is a module in Python that provides functions. These functions help in iterating through iterables.
chain.from_iterable(iterable)
iterables
: This is iterable which needs to be flattened.The method returns a flattened iterable containing all of the input iterable’s elements.
Let’s look at the code below:
from itertools import chainnum_lst1 = [1, 2, 3]num_lst2 = [2, 3, 4]num_lst3 = [3, 5, 6]print("Flattened list of num_lst1, num_lst2 and num_lst3 - ", list(chain.from_iterable([num_lst1, num_lst2, num_lst3])))str_lst1 = ["educative", "edpresso"]print("Flattened list of str_lst1 - ", list(chain.from_iterable(str_lst1)))str_lst2 = ['h', 'e', 'l', 'l', 'o']str_lst1.append(str_lst2)print("new list - ", str_lst1)print("Flattened list of str_lst1 - ", list(chain.from_iterable(str_lst1)))
chain
from the itertools
package.num_lst1
, num_lst2
, and num_lst3
.from_iterable()
method.str_lst1
.from_iterable()
method to flatten str_lst1
to individual characters in the strings.str_lst2
.str_lst2
to str_lst1
.from_iterable()
method to flatten `str_lst1.The output contains the individual characters of the strings and lists in str_lst1
.