Menu Close

Python – How to convert multiple nested list into a single list in python

Here, we will see how to convert multiple nested list into a single list in python. We can achieve this using recursion.

nested_list = [“a”, “b”, [“p”, “q”, [“x”, “y”, [“1”, “2”]]]]

Output: [‘a’, ‘b’, ‘p’, ‘q’, ‘x’, ‘y’, ‘1’, ‘2’]

Algorithm on how to convert multiple nested list into a single list in python:

  • Take one list variable which will store nested list elements in a flatten way.
  • If element of nested list is not a list type then append to flatten list variable.
  • If element is of list type then do recursive call to extract the list element
def get_flat_name(names, flat_name):
    for name in names:
        if not isinstance(name, list):
            flat_name.append(name);
        else:
            # name is a list type so do recursive call to extract element
            get_flat_name(name, flat_name)
    
if __name__ == "__main__":
    names = ["a", "b", ["p", "q", ["x", "y", ["1", "2"]]]]
    flat_name = list()
    
    get_flat_name(names, flat_name)
    
    print (flat_name)

Output:

$ python sample.py

['a', 'b', 'p', 'q', 'x', 'y', '1', '2']

To learn more about python, Please refer given below link:

https://www.techieindoor.com/category/python/

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/pkg/

Posted in Medium, Python

Leave a Reply

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