Python - Convert given list into nested list

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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']]
raja
Published on 22-Jul-2020 08:18:09
Advertisements