Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Convert list into list of lists

Python | Convert list into list of lists

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




# Python3 program to convert
# list into a list of lists
 
def extractDigits(lst):
    res = []
    for el in lst:
        sub = el.split(', ')
        res.append(sub)
     
    return(res)
                 
# Driver code
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




# Python3 program to convert
# list into a list of lists
 
def extractDigits(lst):
    return [[el] for el in lst]
                 
# Driver code
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




# Python3 program to convert
# list into a list of lists
 
def extractDigits(lst):
    return list(map(lambda el:[el], lst))
     
             
# Driver code
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:

  1. Define a function named convert_to_list_of_lists that takes a list lst as an argument.
  2. Inside the function, create an empty list named res to store the results.
  3. Iterate over each element el in the input list lst.
  4. 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.
  5. After iterating over all elements, return the resulting list res.
  6. Create a new list named lst with the elements ‘alice’, ‘bob’, and ‘cara’.
  7. 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.
  8. 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.

RELATED ARTICLES

Most Popular

Recent Comments