- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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.
Example
listA = [[43, [0]],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)
Output
Running the above code gives us the following result −
Given nested list: [[43, [0]], 12, 19, [13, [8, 8]], 21] Flattened List created: [43, 0, 12, 19, 13, 8, 8, 21]
- Related Articles
- Python - Convert given list into nested list
- Python - Convert list of nested dictionary into Pandas Dataframe
- Python - Convert List to custom overlapping nested list
- Convert a string representation of list into list in Python
- Convert set into a list in Python
- 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
- How do make a flat list out of list of lists in Python?
- Python program to convert a list into a list of lists using a step value
- Find maximum length sub-list in a nested list in Python
- Convert a Set into a List in Java
- Convert list of string into sorted list of integer in Python

Advertisements