Convert a list into tuple of lists in Python


Converting one data container into another in python is a frequent requirement. In this article we will take a list and convert into a tuple where each element of the tuple is also a list.

With tuple

We can apply the tuple function straight to the list. But we have to also put a for loop in place so that each element is enclosed in a [].

Example

 Live Demo

listA = ["Mon",2,"Tue",3]
# Given list
print("Given list A: ", listA)
# Use zip
res = tuple([i] for i in listA)
# Result
print("The tuple is : ",res)

Output

Running the above code gives us the following result −

Given list A: ['Mon', 2, 'Tue', 3]
The tuple is : (['Mon'], [2], ['Tue'], [3])

With zip and map

We can also use zip and map in a similar approach as in the above. The map function will apply the list function to each element in the list. Finally the tuple function converts the result into a tuple whose each element is a list.

Example

 Live Demo

listA = ["Mon",2,"Tue",3]
# Given list
print("Given list A: ", listA)
# Use zip
res = tuple(map(list, zip(listA)))
# Result
print("The tuple is : ",res)

Output

Running the above code gives us the following result −

Given list A: ['Mon', 2, 'Tue', 3]
The tuple is : (['Mon'], [2], ['Tue'], [3])

Updated on: 20-May-2020

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements