Python | Convert a nested list into a flat list
The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is there in python list, all the nested has 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 brackets inside.
Examples:
Input : l = [1, 2, [3, 4, [5, 6] ], 7, 8, [9, [10] ] ]
Output : l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Input : l = [[[‘item1’, ‘item2’]], [[‘item3’, ‘item4’]]]
Output : l = [‘item1’, ‘item2’, ‘itm3, ‘item4”]
We use recursion because the levels of nesting cannot be predetermined.
# Python code to flat a nested list with # multiple levels of nesting allowed. # input list l = [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]] # output list output = [] # function used for removing nested # lists in python. def reemovNestings(l): for i in l: if type(i) == list: reemovNestings(i) else: output.append(i) # Driver code print ('The original list: ', l) reemovNestings(l) print ('The list after removing nesting: ', output) |
The original list: [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]] The list after removing nesting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Recommended Posts:
- Python | Convert given list into nested list
- Python | Convert list of nested dictionary into Pandas dataframe
- Python | Check if a nested list is a subset of another nested list
- Python | Find maximum length sub-list in a nested list
- Python | Pair and combine nested list to tuple list
- Python | Convert list of tuples to list of list
- Python | Convert list of string to list of list
- Python | Convert list of numerical string to list of Integers
- Python | Convert list of string into sorted list of integer
- Python | Convert list of tuples to list of strings
- Python | Convert 1D list to 2D list of variable length
- Python | Convert list of strings to list of tuples
- Python | Convert a string representation of list into list
- Python | Convert string enclosed list to list
- Python | Convert list of tuples into list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



