Convert a nested list to an ordinary simple list in Python – Flatten a list
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 that of the nested list in Python.
Flatten a List in Python – Recursive Approach
Given a list of lists, the nesting of lists may occur up to any arbitrary level. By flattening a list, we mean to create a list of all data values in the given list. The data values in the Flattened list appear in the left to right order of their appearance in the original list, ignoring the nested structure of the list. Thus the list,
[1,[2,3],[4,[5,6,[7,8],3],0],10]
will be flattened to obtain the following list:
[1,2,3,4,5,6,7,8,3,0,10]
To create the flattened list, we must initialize list to an empty list and append the data values one by one. The overall approach is summarized below:
for every element i in the list1
{ if i is not in a list
{append int to list2}
otherwise,
{flatten list i}
}
Check: How to make a flat list out of list of lists in Python
SOURCE CODE: Flatten a list in Python
def flatten(list1,list2=[]): ''' Objective : to flatten a list 1 Input parameters :list1,list2 Return value:list2 ''' for element in list1: if type(element)!=list: list2.append(element) else: flatten(element,list2) def main(): ''' Objective : to flatten a list entered by user Input parameter : None Return Value: None ''' list1=eval(input('enter the list: ')) result=flatten(list1) print('flattened list :',result) if __name__=='__main__': main()
If you don’t take user input in this the modified code will be:
def flatten(list1, list2=None): ''' Objective : to flatten a list1 Input parameters : list1, list2 (initialized as an empty list by default) Return value: list2 ''' if list2 is None: list2 = [] for element in list1: if type(element) != list: list2.append(element) else: flatten(element, list2) return list2 # Return the flattened list def main(): ''' Objective : to flatten a predefined list Input parameter : None Return Value: None ''' predefined_list = [1, [2, 3], [4, [5, 6]], 7] result = flatten(predefined_list) print('flattened list:', result) if __name__ == '__main__': main()
Output:
flattened list: [1, 2, 3, 4, 5, 6, 7]
This should be a built-in Python function.