8. python program to flatten a nested list using recursion

Python Program to Flatten a Nested List using Recursion

Given a nested list, the task is to write a python program to flatten a nested list using recursion.

Examples:

Input: [[8, 9], [10, 11, ‘geeks’], [13]]

Output: [8, 9, 10, 11, ‘geeks’, 13]

Input: [[‘A’, ‘B’, ‘C’], [‘D’, ‘E’, ‘F’]]



Output: [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’]

Step-by-step Approach:

  • Firstly, we try to initialize a variable into the linked list.
  • Then, our next task is to pass our list as an argument to a recursive function for flattening the list.
  • In that recursive function, if we find the list as empty then we return the list.
  • Else, we call the function in recursive form along with its sublists as parameters until the list gets flattened.
  • Then finally, we will print the flattened list as output.

Below are some python programs based on the above approach:

Example 1:




# Python program to flatten a nested list
# explicit function to flatten a
# nested list
def flattenList(nestedList):
# check if list is empty
if not(bool(nestedList)):
return nestedList
# to check instance of list is empty or not
if isinstance(nestedList[0], list):
# call function with sublist as argument
return flattenList(*nestedList[:1]) + flattenList(nestedList[1:])
# call function with sublist as argument
return nestedList[:1] + flattenList(nestedList[1:])
# Driver Code
nestedList = [[8, 9], [10, 11, 'geeks'], [13]]
print('Nested List:\n', nestedList)
print("Flattened List:\n", flattenList(nestedList))

Output:

Nested List: [[8, 9], [10, 11, 'geeks'], [13]] Flattened List: [8, 9, 10, 11, 'geeks', 13]

Example 2:




# Python program to flatten a nested list
# explicit function to flatten a
# nested list
def flattenList(nestedList):
# check if list is empty
if not(bool(nestedList)):
return nestedList
# to check instance of list is empty or not
if isinstance(nestedList[0], list):
# call function with sublist as argument
return flattenList(*nestedList[:1]) + flattenList(nestedList[1:])
# call function with sublist as argument
return nestedList[:1] + flattenList(nestedList[1:])
# Driver Code
nestedList = [['A', 'B', 'C'], ['D', 'E', 'F']]
print('Nested List:\n', nestedList)
print("Flattened List:\n", flattenList(nestedList))

Output:

Nested List: [['A', 'B', 'C'], ['D', 'E', 'F']] Flattened List: ['A', 'B', 'C', 'D', 'E', 'F']

Example 3:




# Python program to flatten a nested list
# explicit function to flatten a
# nested list
def flattenList(nestedList):
# check if list is empty
if not(bool(nestedList)):
return nestedList
# to check instance of list is empty or not
if isinstance(nestedList[0], list):
# call function with sublist as argument
return flattenList(*nestedList[:1]) + flattenList(nestedList[1:])
# call function with sublist as argument
return nestedList[:1] + flattenList(nestedList[1:])
# Driver Code
nestedList = [[1], [2], [3], [4], [5]]
print('Nested List:\n', nestedList)
print("Flattened List:\n", flattenList(nestedList))

Output:

Nested List: [[1], [2], [3], [4], [5]] Flattened List: [1, 2, 3, 4, 5]

8. python program to flatten a nested list using recursion




Article Tags :
Python
Python Programs
Technical Scripter
Python list-programs
Technical Scripter 2020

Python Flatten a List using recursive function

PreviousNext

Python's lists can contain other lists.

When one list occurs inside another the inner list is said to be nested inside the outer list.

Each of the inner lists nested within the outer list may also contain nested lists, and those lists may contain additional nested lists to any depth.

For example, the following list includes elements that are nested at several different depths:

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

Flattening a list is the process of converting a list that may contain multiple levels of nested lists into a list that contains all of the same elements without any nesting.

For example, flattening the list from the previous paragraph results in

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

The following recursive algorithm can be used to flatten a list named data :

CopyIf data is empty then Return the empty list If the first element in data is a list then Set l 1 to the result of flattening the first element in data Set l2 to the result of flattening all of the elements in data,\ except the first Return the concatenation of l 1 and l2 If the first element in data is not a list then Set l 1 to a list containing only the first element in data Set l2 to the result of flattening all of the elements in data, \ except the first Return the concatenation of l 1 and l2
Copy## # Use recursion to flatten a list that may contain nested lists. ## from w w w.de m o2 s . co m ## Flatten a list so that all nested lists are removed # @param data the list to flatten # @return a flattened version of data def flatten(data): # If data is empty then there is no work to do if data == []: return [] # If the first element in data is a list if type (data[0]) == list : # Flatten the first element and flatten the remaining elements in the list return flatten(data[0]) + flatten(data[1:]) else : # The first element in data is not a list so # only the remaining elements in the list need # to be flattened return [data[0]] + flatten(data[1:]) print (flatten([1,[2,3],[4,[5,[6,7]]],[[[8],9],[10]]])) print (flatten([1,[2,[3,[4,[5,[6,[7,[8,[9,[10]]]]]]]]]])) print (flatten([[[[[[[[[[1],2],3],4],5],6],7],8],9],10])) print (flatten([1,2,3,4,5,6,7,8,9,10])) print (flatten([]))

Result

By Pavitra Walia

In this tutorial, we will be discussing the concept of flattening a list. By the end of the tutorial, you will be able to convert a nested list to an ordinary simple list in the same order as the that of the nested list.

Python flatten a nested list or list of lists

8. python program to flatten a nested list using recursion

Overview

Problem: Given a list of lists in Python; how to flatten the list?

Now, some of you might be thinking what does flattening a list actually mean? ?

Answer:

Flattening a list is the process used to convert a multidimensional or nested list (list of lists) into a one-dimensional list. Let’s have a look at an example to get a clearer picture of flattening a list.

Example: Consider the given list as shown below.

[[10,20],[30,40,50]]

After flattening the list it looks something like this:

[10,20,30,40,50]

❖ Types Of List Flattening

8. python program to flatten a nested list using recursion

Shallow Flattening is the process of flattening lists that only have a depth of one-level.

Example: Consider the list as given below (it represents a list that one-level depth)

li = [[100,200],[300,400]]

Flattened (Shallow) List:

[100,200,300,400,500]

Deep Flattening is the process of flattening lists that have varying depths.

Example: Consider the given list given below (it represents a list of varying depth).

l = [ [100,150], [ [200 ] ], [ 300, 400 ] ]

Flattened (Deep) List:

[100,150,200,300,400]

Now that we know what flattening means and its types, let us understand how we can flatten lists. Without further delay, let the games begin!