Open In App

Python – Convert List of Lists to Tuple of Tuples

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

The 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))


Output

The 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:

  1. Define the function list_to_tuple(lst) that takes a list lst as input.
  2. Check if the length of the list is 0. If it is, return an empty tuple ().
  3. 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.
  4. 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


Output

The 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

  1. Iterate through each element of each sublist in the original list of lists. 
  2. For each sublist, it creates a new tuple by iterating through the elements of the sublist and adding each element to the tuple. 
  3. 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))


Output

The 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:

  1. Import the itertools module.
  2. Define a function that accepts a list and returns a tuple of the same list.
  3. Pass the list of lists as an argument to the itertools.starmap() function along with the function defined in step 2.
  4. Convert the output of step 3 to a tuple using the tuple() function.
  5. 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))


Output

The 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:

  1. Define a function named list_to_tuple that takes a single argument, lst.
  2. Use a nested list comprehension to iterate over the nested list and convert each inner list to a tuple.
  3. Use the zip function to transpose the resulting list of tuples into a tuple of tuples.
  4. 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))


Output

The 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 Program to Convert Tuple Value List to List of Tuples
Given a dictionary with values as a tuple list, convert it to a key-mapped list of tuples. Input : test_dict = {'Gfg' : [(5, ), (6, )], 'is' : [(5, )], 'best' :[(7, )]} Output : [('Gfg', 5), ('Gfg', 6), ('is', 5), ('best', 7)] Explanation : Keys grouped with values.Convert Tuple Value List to List of Tuples Using loop + * operator + items() This is
8 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
Python Program to Convert Tuple Matrix to Tuple List
Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]] Output : [(4, 10), (5, 13)] Explanation : All co
8 min read
Python | Convert list of tuples to dictionary value lists
One among the problem of interconversion of data types in python is conversion of list of tuples to dictionaries, in which the keys are 1st elements of tuple, which are uniquely identified as keys in dictionary and it's corresponding value as a list of the corresponding value of respective keys as tuple's second element. Let's discuss how to solve
9 min read
Convert Set of Tuples to a List of Lists in Python
Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list. You will be guided through the ideas and procedu
3 min read
Convert List of Tuples To Multiple Lists in Python
Managing data often entails working with tuples of information, particularly when working with datasets. For more easy processing, these tuples can sometimes need to be split up into numerous lists. In this article, we will see how to convert list of tuples to multiple lists in Python. Convert List of Tuples to Multiple Lists in PythonBelow are som
3 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] Method #1 : Using pow() function.We can use list compreh
5 min read
Python | Convert a list into tuple of lists
We are given a list, the task is to convert the list into tuple of lists. Input: ['Geeks', 'For', 'geeks'] Output: (['Geeks'], ['For'], ['geeks'])Input: ['first', 'second', 'third'] Output: (['first'], ['second'], ['third']) Method #1: Using Comprehension C/C++ Code # Python code to convert a list into tuple of lists # Initialisation of list Input
4 min read
Python - Convert List to Single valued Lists in Tuple
Conversion of data types is the most common problem across CS domain nowdays. One such problem can be converting List elements to single values lists in tuples. This can have application in data preprocessing domain. Let's discuss certain ways in which this task can be performed. Input : test_list = [1, 3, 5, 6, 7, 9] Output : ([1], [3], [5], [6],
7 min read
Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read