- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert a nested list into a flat list in Python
A nested list is a list whose elements are lists themselves. If we have a python data container which is a nested list, we may sometimes need to convert it into a flattened list so that each element can be processed further.
Even the inner elements can also be nested themselves. And there can be many layers of nesting. So we will approach this problem with recursion. We will keep checking if the element is nested and then keep going applying the function again and again until the element is no longer a list. Once it is found that element is not a list, we will append it to a new list which will hold all the non-nested elements of the list.
listA = [[43, ],12, 19, [13,[8, 8]], 21 ] print('Given nested list: \n', listA) # Flat List res =  # function def flatlist(l): for x in l: if type(x) == list: flatlist(x) else: res.append(x) flatlist(listA) print('Flattened List created: \n', res)
Running the above code gives us the following result −
Given nested list: [[43, ], 12, 19, [13, [8, 8]], 21] Flattened List created: [43, 0, 12, 19, 13, 8, 8, 21]
- Python - Convert given list into nested list
- Python - Convert list of nested dictionary into Pandas Dataframe
- Convert set into a list in Python
- Convert a list into a tuple in Python.
- Convert a string representation of list into list in Python
- Python - Convert List to custom overlapping nested list
- Convert key-values list to flat dictionary in Python
- Convert list into list of lists in Python
- Convert list of tuples into list in Python
- How to convert a list into a tuple in Python?
- Convert a list into tuple of lists in Python
- Convert a Set into a List in Java
- Python program to convert a list into a list of lists using a step value
- How do make a flat list out of list of lists in Python?
- Python program to convert a list of characters into a string