Flatten A List – A Recursive Approach For Problems On Lists

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.

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}
}

How to make a flat list out of list of lists in Python



How to Perform Matrix Multiplication of given dimension in Python3?

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()

Also learn,

Leave a Reply

Your email address will not be published. Required fields are marked *