Open In App

Python | Convert given list into nested list

Last Updated : 07 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, we come across data that is in string format in a list and it is required to convert it into a list of the list. This kind of problem of converting a list of strings to a nested list is quite common in web development. Let’s discuss certain ways in which this can be performed.

Convert the Given List into Nested List in Python

Below are the ways by which we can convert a given list into a Nested List in Python:

  • Using iteration
  • Using a list with numeric values 
  • Using map(), split() and lambda
  • Using list comprehension
  • Using numpy library
  • Using heapq

Convert the Given List into Nested List Using Iteration

In this example, the Python code takes a list of strings, where each string contains comma-separated values, and converts it into a list of lists. It achieves this by first splitting each string into individual elements and then organizing them into sublists, resulting in the desired list of lists named “Output”.

Python3




# List initialization
Input = ['Geeeks, Forgeeks', '65.7492, 62.5405',
         'Geeks, 123', '555.7492, 152.5406']
 
temp = []
 
# Getting elem in list of list format
for elem in Input:
    temp2 = elem.split(', ')
    temp.append((temp2))
 
# List initialization
Output = []
 
for elem in temp:
    temp3 = []
    for elem2 in elem:
        temp3.append(elem2)
    Output.append(temp3)
 
# printing
print(Output)


Output

[['Geeeks', 'Forgeeks'], ['65.7492', '62.5405'], ['Geeks', '123'], ['555.7492', '152.5406']]

Python Convert List into Nested List Using List With Numeric Values

In this example, the Python code utilizes the ast.literal_eval function to safely convert a list of comma-separated string elements (Input) into a list of lists (Output) containing numerical values, demonstrating an approach that ensures proper evaluation and avoids potential security risks.

Python3




# importing
import ast
 
# List Initialization
Input = ['12, 454', '15.72, 82.85', '52.236, 25256', '95.9492, 72.906']
 
# using ast to convert
Output = [list(ast.literal_eval(x)) for x in Input]
 
# printing
print(Output)


Output

[[12, 454], [15.72, 82.85], [52.236, 25256], [95.9492, 72.906]]

Time complexity: O(n), where n is the length of the input list Input. 
Auxiliary space: O(n), where n is the length of the input list Input. 

Convert Python List into Nested List Using map(), split() and lambda

We use the map function to apply a function (in this case, the split function) to each element in a list (in this case, the list of strings). The map function returns an iterator that applies the function to each element of the list, and returns the results as a new iterator. To obtain the final result as a list, we use the list function to convert the iterator returned by map into a list.

Python3




# initializing list of strings
Input = ['Geeeks, Forgeeks', '65.7492, 62.5405',
         'Geeks, 123', '555.7492, 152.5406']
 
Output = list(map(lambda x: x.split(', '), Input))
print("Result: "+str(Output))


Output

Result: [['Geeeks', 'Forgeeks'], ['65.7492', '62.5405'], ['Geeks', '123'], ['555.7492', '152.5406']]

Time complexity: O(n)
Auxiliary Space: O(n)

Turning a List into Nested Lists in Python Using List Comprehension

The program converts a list of strings into a list of lists by splitting each string by a comma followed by a space. In this example, the Python code initializes a list of strings (Input) with comma-separated values. It employs list comprehension to split each string into elements and create a list of lists (output). The result is then printed, showcasing a concise approach for transforming the input strings into organized sublists.

Python3




# List initialization
Input = ['Geeeks, Forgeeks', '65.7492, 62.5405',
         'Geeks, 123', '555.7492, 152.5406']
 
# Using list comprehension to convert
# element into list of list
output = [elem.split(', ') for elem in Input]
 
# printing
print(output)


Output

[['Geeeks', 'Forgeeks'], ['65.7492', '62.5405'], ['Geeks', '123'], ['555.7492', '152.5406']]

Time complexity: O(n), where n is the number of strings in Input. 
Auxiliary Space: O(n), because the resulting list output has n sublists, each containing two elements.

Python Convert List into Nested List Using numpy

In this example, the Python code leverages NumPy to transform a list of strings (Input) with comma-separated values into a NumPy array (output). The array is created using list comprehension and then converted back to a nested list for printing.

Python3




import numpy as np
 
Input = ['Geeeks, Forgeeks', '65.7492, 62.5405',
         'Geeks, 123', '555.7492, 152.5406']
 
output = np.array([elem.split(', ') for elem in Input])
print(output.tolist())


Output:

[['Geeeks', 'Forgeeks'], ['65.7492', '62.5405'], ['Geeks', '123'], ['555.7492', '152.5406']]

Time complexity: O(n)
Auxiliary Space: O(n)

Python Turning a List into Nested Lists Using heapq

In this example, the Python code utilizes the heapq module to create a min-heap (output) of lists resulting from splitting strings in a list (Input) with comma-separated values. The min-heap is then popped to retrieve the elements in ascending order, demonstrating the use of heaps for ordered processing.

Python3




import heapq
 
Input = ['Geeeks, Forgeeks', '65.7492, 62.5405',
         'Geeks, 123', '555.7492, 152.5406']
 
output = []
for elem in Input:
    heapq.heappush(output, elem.split(', '))
 
output = [heapq.heappop(output) for i in range(len(output))]
print(output)


Output

[['555.7492', '152.5406'], ['65.7492', '62.5405'], ['Geeeks', 'Forgeeks'], ['Geeks', '123']]

Time complexity: O(n log n)
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Convert list of nested dictionary into Pandas dataframe
Given a list of the nested dictionary, write a Python program to create a Pandas dataframe using it. We can convert list of nested dictionary into Pandas DataFrame. Let's understand the stepwise procedure to create a Pandas Dataframe using the list of nested dictionary. Convert Nested List of Dictionary into Pandas DataframeBelow are the methods th
4 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Python | Convert nested sublist into tuples
Sometimes, while working with huge amount of data, we might have in which each point of data constitutes of several elements and needs to be processed as single unit. For this, we might sometimes, just receive a matrix and it's constituent data points are also lists, which don't make much sense and whole and might be required to be converted to tup
8 min read
Python | Convert string List to Nested Character List
Sometimes, while working with Python, we can have a problem in which we need to perform interconversion of data. In this article we discuss converting String list to Nested Character list split by comma. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() The combination of above functional
7 min read
Python - Convert List to custom overlapping nested list
Given a list, the task is to write a Python program to convert it into a custom overlapping nested list based on element size and overlap step. Examples: Input: test_list = [3, 5, 6, 7, 3, 9, 1, 10], step, size = 2, 4Output: [[3, 5, 6, 7], [6, 7, 3, 9], [3, 9, 1, 10], [1, 10]]Explanation: Rows sliced for size 4, and overcoming started after 2 eleme
3 min read
Python | Split nested list into two lists
Given a nested 2D list, the task is to split the nested list into two lists such that the first list contains the first elements of each sublist and the second list contains the second element of each sublist. In this article, we will see how to split nested lists into two lists in Python. Python Split Nested List into Two ListsBelow are the ways b
5 min read
Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Convert Nested Dictionary to List Python
Python dictionaries are versatile data structures that allow the storage of key-value pairs. However, working with nested dictionaries, where values themselves are dictionaries, can sometimes be challenging. In this article, we will explore various simple and commonly used methods to convert a nested dictionary into a list in Python. Example: Input
3 min read
Practice Tags :