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://techieindoor.com/category/python/
https://techieindoor.com/go-lang-tutorial/
References: