Python | Convert list into list of lists
Last Updated :
08 May, 2023
Given a list of strings, write a Python program to convert each element of the given list into a sublist. Thus, converting the whole list into a list of lists.
Examples:
Input : ['alice', 'bob', 'cara']
Output : [['alice'], ['bob'], ['cara']]
Input : [101, 202, 303, 404, 505]
Output : [[101], [202], [303], [404], [505]]
Approach #1 : Naive Approach Use another list ‘res’ and a for a loop. Using split() method of Python we extract each element from the list in the form of the list itself and append it to ‘res’. Finally, return ‘res’. One drawback of this method is that it does not work with integer list as ‘int’ object has no attribute ‘split’.
Python3
def extractDigits(lst):
res = []
for el in lst:
sub = el.split( ', ' )
res.append(sub)
return (res)
lst = [ 'alice' , 'bob' , 'cara' ]
print (extractDigits(lst))
|
Output:
[['alice'], ['bob'], ['cara']]
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach #2 : List comprehension List comprehension is an efficient approach as it doesn’t make use of extra space. For each element ‘el’ in list, it simply appends [el] to the output list.
Python3
def extractDigits(lst):
return [[el] for el in lst]
lst = [ 'alice' , 'bob' , 'cara' ]
print (extractDigits(lst))
|
Output:
[['alice'], ['bob'], ['cara']]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
Approach #3 : Python map() The given code maps the function el:[el] for each item of the given iterable ‘lst’. Hence outputs each element as a list itself.
Python3
def extractDigits(lst):
return list ( map ( lambda el:[el], lst))
lst = [ 'alice' , 'bob' , 'cara' ]
print (extractDigits(lst))
|
Output:
[['alice'], ['bob'], ['cara']]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as a new list is created to store the transformed elements.
Approach #4: Using List Comprehension with map() function
In this approach, we can combine the use of list comprehension and the map() function to achieve the desired result. The map() function applies the lambda function to each element of the input list ‘lst’, which returns a list with each element enclosed in a list. The list comprehension then iterates over the resulting mapped list and returns the final list of lists.
Step-by-step approach:
- Define a lambda function that takes an element of the input list ‘lst’ and returns it enclosed in a list.
- Use the map() function to apply the lambda function to each element of ‘lst’ and return a list of lists.
- Use a list comprehension to iterate over the resulting list of lists and return the final output list.
- Define the ‘extractDigits’ function that takes the input list ‘lst’ as an argument and returns the output list.
- Call the ‘extractDigits’ function with the input list ‘lst’ as an argument.
- Print the output list returned by the ‘extractDigits’ function.
Python3
def extractDigits(lst):
return [x for x in map ( lambda el: [el], lst)]
lst = [ 'alice' , 'bob' , 'cara' ]
print (extractDigits(lst))
|
Output
[['alice'], ['bob'], ['cara']]
Time complexity: O(n), where n is the length of the input list ‘lst’.
Auxiliary space: O(n), where n is the length of the input list ‘lst’.
Method 5 : use the list() constructor and iterate over the elements of the original list, creating a list with each element as the sole member of the sublist
step-by-step approach of the program:
- Define a function named convert_to_list_of_lists that takes a list lst as an argument.
- Inside the function, create an empty list named res to store the results.
- Iterate over each element el in the input list lst.
- For each element, create a new list containing el as its sole member using square brackets notation and append it to the res list using the append() method.
- After iterating over all elements, return the resulting list res.
- Create a new list named lst with the elements ‘alice’, ‘bob’, and ‘cara’.
- Call the convert_to_list_of_lists function with the lst list as an argument and store the resulting list in a variable named res.
- Print the resulting list res using the print() function.
Python3
def convert_to_list_of_lists(lst):
res = []
for el in lst:
res.append([el])
return res
lst = [ 'alice' , 'bob' , 'cara' ]
res = convert_to_list_of_lists(lst)
print (res)
|
Output
[['alice'], ['bob'], ['cara']]
In terms of time complexity, this implementation has a linear time complexity O(n), where n is the length of the input list, since it iterates over each element of the input list exactly once.
In terms of auxiliary space, it has an auxiliary space complexity of O(n), since it creates a new list to store each element of the input list.
Using numpy:
Algorithm:
- Import the numpy library using the statement import numpy as np.
- Define a function named convert_to_list_of_lists that takes a list lst as its input.
- Inside the function, convert the input list lst into a numpy array using the statement np.array(lst).
- Reshape the numpy array into a 2D array with a single column using the statement np.array(lst).reshape(-1, 1).
- Convert the numpy array into a list of lists using the tolist() method.
- Return the resulting list of lists from the function.
- Define a list lst with some values.
- Call the convert_to_list_of_lists function with the input list lst and store the result in a variable named res.
- Print the result res.
Python3
import numpy as np
def convert_to_list_of_lists(lst):
return np.array(lst).reshape( - 1 , 1 ).tolist()
lst = [ 'alice' , 'bob' , 'cara' ]
res = convert_to_list_of_lists(lst)
print (res)
|
Output:
[['alice'], ['bob'], ['cara']]
Time complexity: O(n), where n is the length of the input list ‘lst’.
Auxiliary space: O(n), where n is the length of the input list ‘lst’. The numpy array and list created have the same length as the input list, so the space complexity is linear in the input size.
Similar Reads
Python - Convert a list into tuple of lists
When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists. For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this co
3 min read
Python | Convert list of tuples into list
In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read
Python - Convert List of Dictionaries to List of Lists
We are given list of dictionaries we need to convert it to list of lists. For example we are given a list of dictionaries a = [{'name': 'Geeks', 'age': 25}, {'name': 'Geeks', 'age': 30}] we need to convert it in list of list so that the output becomes[['Geeks',25],['Geeks;'30]]. Using List Comprehen
3 min read
Convert a List of Lists into Tree-like Dict - Python
We are given a list of lists we need to convert it into tree-like dictionary. For example we are given a list of list li = [["a", "b", "c"], ["a", "b", "d"], ["x", "y"]] we need to convert it into tree like dict so that the output should be like {'a': {'b': {'c': {}, 'd': {}}}, 'x': {'y': {}}} .We c
5 min read
Python - Convert List to List of dictionaries
We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
4 min read
Convert List of Lists to Dictionary - Python
We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Python | Convert given list into nested list
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
5 min read
Python - Convert List of lists to list of Sets
We are given a list containing lists, and our task is to convert each sublist into a set. This helps remove duplicate elements within each sublist. For example, if we have: a = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] The output should be: [{1, 2}, {1, 2, 3}, {2}, {0}] Let's explore some method's t
2 min read
Python - Convert Key-Value list Dictionary to List of Lists
We are given a key value list dictionary we need to convert it list of lists. For example we are given a dictionary a = {'name': 'Geeks', 'age': 8, 'city': 'Noida'} we need to convert this into list of lists so the output should be [['name', 'Geeks'], ['age', 25], ['city', 'Geeks']]. Using List Comp
3 min read
Python | Convert List of lists to list of Strings
Interconversion of data is very popular nowadays and has many applications. In this scenario, we can have a problem in which we need to convert a list of lists, i.e matrix into list of strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + joi
4 min read