
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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]
Advertisements