
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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])
Advertisements