Python Program to Flatten a Nested List using Recursion
Last Updated :
14 Mar, 2023
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:
Python3
# 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]
the time complexity can be O(n^2), where n is the total number of elements in the list.
the space complexity can be O(n), where n is the total number of elements in the list.
Example 2:
Python3
# 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']
The time complexity of the provided program is O(n), where n is the total number of elements in the input nested list.
The auxiliary space complexity of the program is also O(n), where n is the total number of elements in the input nested list.
Example 3:
Python3
# 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]
Similar Reads
Python Program to Flatten a List without using Recursion The task is to convert a nested list into a single list in Python i.e no matter how many levels of nesting are there in the Python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brack
7 min read
Python Program to Find the Total Sum of a Nested List Using Recursion A nested list is given. The task is to print the sum of this list using recursion. A nested list is a list whose elements can also be a list. Examples : Input: [1,2,[3]] Output: 6 Input: [[4,5],[7,8,[20]],100] Output: 144 Input: [[1,2,3],[4,[5,6]],7] Output: 28 Recursion: In recursion, a function ca
5 min read
Python program to Flatten Nested List to Tuple List Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted ar
7 min read
Python | Sort Flatten list of list The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a l
7 min read
Python | Flatten Tuples List to String Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + join() The
7 min read