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
# 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:
- 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 Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read