How to flatten a list of iterables in Python

Overview

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.

Syntax

chain.from_iterable(iterable)

Parameters

  • iterables: This is iterable which needs to be flattened.

Return value

The method returns a flattened iterable containing all of the input iterable’s elements.

Code example

Let’s look at the code below:

from itertools import chain
num_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)))

Code explanation

  • Line 1: We import chain from the itertools package.
  • Lines 3 to 5: We define three lists, num_lst1, num_lst2, and num_lst3.
  • Line 6: The lists are flattened using the from_iterable() method.
  • Line 8: We define a list of strings called str_lst1.
  • Line 9: We use the from_iterable() method to flatten str_lst1 to individual characters in the strings.
  • Line 11: We define a list of characters called str_lst2.
  • Line 12: We append str_lst2 to str_lst1.
  • Line 14: We use the from_iterable() method to flatten `str_lst1.

Output

The output contains the individual characters of the strings and lists in str_lst1.

Free Resources