Q:

Python | Convert List of Lists to Tuple of Tuples

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Tuple to tuples is a nested collection in which a tuple consists of tuples as elements.

List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered sets of values enclosed in square brackets [].

List of Lists is a nested collection in which a list consists of lists as elements.

Converting List of Lists to Tuple of Tuples

We have a list of lists and we will be converting it to a tuple of tuples.

For this, we will be taking each tuple from the tuple to tuples and converting it into a tuple. And then convert the whole encapsulating list to a tuple. In python, we can perform this task using multiple ways.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One way to solve the problem is by converting each list of the list of list to tuple individually using tuple() method. And then converting the main container. This is done using list comprehension along with the tuple() method.

# Python program to Convert list of lists 
# to Tuple of Tuples 

# Initializing and printing List of lists 
listOflists = [[4, 1, 9], [2, 6, 8], [5, 9, 1]]
print("Initial List of Lists : " + str(listOflists))
  
# Converting List of Lists to Tuple of Tuples
convTupleOfTuple = tuple(tuple(data) for data in listOflists)
  
# Printing the Tuple of Tuples
print("Converted Tuple of Tuples : " + str(convTupleOfTuple))

Output:

Initial List of Lists : [[4, 1, 9], [2, 6, 8], [5, 9, 1]]
Converted Tuple of Tuples : ((4, 1, 9), (2, 6, 8), (5, 9, 1))

Method 2:

One method that can solve the problem is by using map() to map the converted individual list which will be converted using tuple() method.

# Python program to Convert list of lists 
# to Tuple of Tuples 

# Initializing and printing List of lists 
listOflists = [[4, 1, 9], [2, 6, 8], [5, 9, 1]]
print("Initial List of Lists : " + str(listOflists))
  
# Converting List of Lists to Tuple of Tuples
convTupleOfTuple = tuple(map(tuple, listOflists))
  
# Printing the Tuple of Tuples
print("Converted Tuple of Tuples : " + str(convTupleOfTuple))

Output:

Initial List of Lists : [[4, 1, 9], [2, 6, 8], [5, 9, 1]]
Converted Tuple of Tuples : ((4, 1, 9), (2, 6, 8), (5, 9, 1))

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Flatten Nested Tuples... >>
<< Python | Multiple Keys Grouped Summation...