Python - Convert List of Lists to Tuple of Tuples
Last Updated :
15 May, 2023
Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let us discuss certain ways in which this task can be performed.
Input : test_list = [['Best'], ['Gfg'], ['Gfg']]
Output : (('Best', ), ('Gfg', ), ('Gfg', ))
Input : test_list = [['Gfg', 'is', 'Best']]
Output : (('Gfg', 'is', 'Best'), )
Method #1: Using tuple() + list comprehension
The combination of the above functions can be used to solve this problem. In this, we perform the conversion using tuple(), and list comprehension is used to extend the logic to all the containers.
Python3
# Python3 code to demonstrate working of
# Convert List of Lists to Tuple of Tuples
# using tuple + list comprehension
# Initializing list
test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],
['Gfg', 'is', 'for', 'Geeks']]
# Printing original list
print("The original list is : " + str(test_list))
# Convert List of Lists to Tuple of Tuples
# using tuple + list comprehension
res = tuple(tuple(sub) for sub in test_list)
# Printing result
print("The converted data : " + str(res))
OutputThe original list is : [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'], ['Gfg', 'is', 'for', 'Geeks']]
The converted data : (('Gfg', 'is', 'Best'), ('Gfg', 'is', 'love'), ('Gfg', 'is', 'for', 'Geeks'))
Time complexity: O(n*m), where n is the length of the input list and m is the length of the longest sublist.
Auxiliary Space: O(n*m), as the program creates a new tuple for each sublist in the input list, and each tuple contains the elements of the corresponding sublist. Therefore, the space used is proportional to the total number of elements in the input list.
Method #2 : Using map() + tuple()
The combination of the above functions can be used to solve this problem. In this, we perform the task performed using list comprehension using map(), to extend the conversion logic to each sublist.
Python3
# Python3 code to demonstrate working of
# Convert List of Lists to Tuple of Tuples
# Using map() + tuple()
# Initializing list
test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],
['Gfg', 'is', 'for', 'Geeks']]
# Printing original list
print("The original list is : " + str(test_list))
# Convert List of Lists to Tuple of Tuples
# using map() + tuple()
res = tuple(map(tuple, test_list))
# Printing result
print("The converted data : " + str(res))
OutputThe original list is : [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'], ['Gfg', 'is', 'for', 'Geeks']]
The converted data : (('Gfg', 'is', 'Best'), ('Gfg', 'is', 'love'), ('Gfg', 'is', 'for', 'Geeks'))
Time complexity: O(n*m), where n is the number of sublists in the input list and m is the maximum length of a sublist.
Auxiliary space: O(n*m), since the tuple() function creates a new tuple for each sublist in the input list, and each tuple contains m elements.
Method #3: Using enumerate function
Python3
# Initializing list
test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],
['Gfg', 'is', 'for', 'Geeks']]
res = tuple(tuple(i) for a, i in enumerate(test_list))
# Printing result
print((res))
Output(('Gfg', 'is', 'Best'), ('Gfg', 'is', 'love'), ('Gfg', 'is', 'for', 'Geeks'))
Time complexity: O(N*M), where N is the length of test_list and M is the maximum length of a sublist in test_list.
Auxiliary space: O(N*M)
Method#4: Using Recursive method
Algorithm:
- Define the function list_to_tuple(lst) that takes a list lst as input.
- Check if the length of the list is 0. If it is, return an empty tuple ().
- If lst is not empty, convert the first element of list to a tuple using the tuple function, and add it to the result of calling list_to_tuple recursively on the rest of list.
- Return the tuple obtained in step 3.
Python3
def list_to_tuple(lst):
if len(lst) == 0:
return ()
else:
return (tuple(lst[0]),) + list_to_tuple(lst[1:])
# Initializing list
test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],
['Gfg', 'is', 'for', 'Geeks']]
# Printing original list
print("The original list is : " + str(test_list))
res = list_to_tuple(test_list)
# Printing result
print("The converted data : " + str(res))
# this code contributed by tvsk
OutputThe original list is : [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'], ['Gfg', 'is', 'for', 'Geeks']]
The converted data : (('Gfg', 'is', 'Best'), ('Gfg', 'is', 'love'), ('Gfg', 'is', 'for', 'Geeks'))
Time complexity:O(N), The function list_to_tuple is called recursively on a list that is one element smaller than the previous list, until the length of the list becomes 0. The number of times the function is called recursively is equal to the length of the input list. Therefore, the time complexity of the function is O(n), where n is the length of the input list.
Auxiliary space:O(N), The function list_to_tuple uses a constant amount of space to store the empty tuple (), which is returned when the input list is empty. In addition, the function creates a tuple for each element in the input list using the tuple function. Since each tuple created in the function is of the same length as the input list, the space complexity of the function is O(n), where n is the length of the input list.
Method #5: Using nested loops
- Iterate through each element of each sublist in the original list of lists.
- For each sublist, it creates a new tuple by iterating through the elements of the sublist and adding each element to the tuple.
- It then appends the new tuple to a new list before creating a final tuple containing all the sub-tuples.
Python3
# Initializing list
test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],
['Gfg', 'is', 'for', 'Geeks']]
# Printing original list
print("The original list is : " + str(test_list))
# Convert List of Lists to Tuple of Tuples
# using nested loops
# Empty list
res = []
for sub in test_list:
tup = ()
for ele in sub:
tup += (ele,)
res.append(tup)
res = tuple(res)
# Printing result
print("The converted data : " + str(res))
OutputThe original list is : [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'], ['Gfg', 'is', 'for', 'Geeks']]
The converted data : (('Gfg', 'is', 'Best'), ('Gfg', 'is', 'love'), ('Gfg', 'is', 'for', 'Geeks'))
Time complexity: O(n^2) where n is the number of elements in the list of lists.
Auxiliary Space: O(n^2) because we are creating a new tuple for each sublist and then adding those tuples to a new list before creating a final tuple containing all the sub-tuples.
Method #6: Using itertools.starmap()
Approach:
- Import the itertools module.
- Define a function that accepts a list and returns a tuple of the same list.
- Pass the list of lists as an argument to the itertools.starmap() function along with the function defined in step 2.
- Convert the output of step 3 to a tuple using the tuple() function.
- Store the result in a variable and print it.
Python
# Python3 code to demonstrate working of
# Convert List of Lists to Tuple of Tuples
# using itertools.starmap()
# Importing module
import itertools
# Initializing list
test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],
['Gfg', 'is', 'for', 'Geeks']]
# Printing original list
print("The original list is : " + str(test_list))
# Function
# To convert list to tuple
def list_to_tuple(*args):
return tuple(args)
# Using itertools.starmap()
res = tuple(itertools.starmap(list_to_tuple, test_list))
# Printing result
print("The converted data : " + str(res))
OutputThe original list is : [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'], ['Gfg', 'is', 'for', 'Geeks']]
The converted data : (('Gfg', 'is', 'Best'), ('Gfg', 'is', 'love'), ('Gfg', 'is', 'for', 'Geeks'))
Time complexity: O(n), where n is the total number of elements in the input list of lists.
Auxiliary space: O(n), where n is the total number of elements in the input list of lists.
Method #7: Using a nested list comprehension and zip() function
This method involves using a nested list comprehension to iterate over the nested list and convert each inner list to a tuple. The zip function is then used to transpose the resulting list of tuples into a tuple of tuples.
Steps:
- Define a function named list_to_tuple that takes a single argument, lst.
- Use a nested list comprehension to iterate over the nested list and convert each inner list to a tuple.
- Use the zip function to transpose the resulting list of tuples into a tuple of tuples.
- Return the resulting tuple of tuples.
Python3
def list_to_tuple(lst):
return tuple(tuple(inner_lst) for inner_lst in lst)
# Initializing list
test_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'],
['Gfg', 'is', 'for', 'Geeks']]
# Printing original list
print("The original list is : " + str(test_list))
res = list_to_tuple(test_list)
# Printing result
print("The converted data : " + str(res))
OutputThe original list is : [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'], ['Gfg', 'is', 'for', 'Geeks']]
The converted data : (('Gfg', 'is', 'Best'), ('Gfg', 'is', 'love'), ('Gfg', 'is', 'for', 'Geeks'))
Time complexity: O(n^2), where n is the length of the nested list.
Auxiliary space: O(n^2), for storing the tuple of tuples.
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
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 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
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