Python Program to Flatten a Nested List using Recursion


When it is required to flatten a given nested list using recursion technique, simple indexing, and the ‘isinstance’ method can be used along with recursion.

The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.

Example

Below is a demonstration for the same −

 Live Demo

def flatten_list(my_list):
   if my_list == []:
      return my_list
   if isinstance(my_list[0], list):
      return flatten_list(my_list[0]) + flatten_list(my_list[1:])
   return my_list[:1] + flatten_list(my_list[1:])
my_list = [[1,2],[3,4], [90, 11], [56, 78], [[34,56]]]
print("The list is :")
print(my_list)
print("The list after flattening is : ")
print(flatten_list(my_list))

Output

The list is :
[[1, 2], [3, 4], [90, 11], [56, 78], [[34, 56]]]
The list after flattening is :
[1, 2, 3, 4, 90, 11, 56, 78, 34, 56]

Explanation

  • A method named ‘flatten_list’ is defined, that takes a list as parameter.
  • It checks to see the data type of the first element in the list.
  • If it matches to a list, then, the first element along with the second element to last element is concatenated and displayed.
  • This results in a nested list being flattened.
  • Otherwise, the first element is left out, and the list is first reversed and the normal list is combined, and returned as output.
  • Outside the function, a nested list is defined, and is displayed on the console.
  • The method is called by passing the list as parameter.
  • The output is displayed on the console.

Updated on: 12-Mar-2021

778 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements