
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 Given List into Nested List in Python
There may be a situation when we need to convert the elements in the list into a list in itself. In other words, create a list which is nested as its elements are also lists.
Using iteration
This is the novel approach in which we take each element of the list and convert it to a format of lists. We use temporary list to achieve this. Finally all these elements which are converted to lists are group together to create the required list of lists.
Example
listA = ['Mon','Tue','Wed','Thu','Fri'] print("Given list:\n",listA) new_list = [] # Creating list of list format for elem in listA: temp = elem.split(', ') new_list.append((temp)) # Final list res = [] for elem in new_list: temp = [] for e in elem: temp.append(e) res.append(temp) # printing print("The list of lists:\n",res)
Output
Running the above code gives us the following result −
Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of lists: [['Mon'], ['Tue'], ['Wed'], ['Thu'], ['Fri']]
With ast
We can also use the python module names abstract syntax trees or called ast. It has a function named literal_eval which will keep the elements of the given list together and convert it to a new list.
Example
import ast listA = ['"Mon","Tue"','"Wed","Thu","Fri"'] print("Given list: \n", listA) res = [list(ast.literal_eval(x)) for x in listA] # New List print("The list of lists:\n",res)
Output
Running the above code gives us the following result −
Given list: ['"Mon","Tue"', '"Wed","Thu","Fri"'] The list of lists: [['Mon', 'Tue'], ['Wed', 'Thu', 'Fri']]
Advertisements