VOOZH about

URL: https://www.geeksforgeeks.org/python/python-convert-integral-list-to-tuple-list/

⇱ Python | Convert Integral list to tuple list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python | Convert Integral list to tuple list

Last Updated : 12 Apr, 2023

Sometimes, while working with data, we can have a problem in which we need to perform type of interconversions of data. There can be a problem in which we may need to convert integral list elements to single element tuples. Let's discuss certain ways in which this task can be performed. 
Method #1 : Using list comprehension List comprehension can be used as a shorthand method to solve this particular problem. In this, we iterate through the list and convert each integer element into a tuple object. 


Output
The original list : [1, 4, 6, 8, 9]
List after conversion to tuple list : [(1,), (4,), (6,), (8,), (9,)]

Time Complexity: O(n), where n is the length of the input list. This is because we’re using list comprehension which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

 Method #2 : Using zip() + list() This is the simplest method to perform this particular task. The zip() when applied to list of integers, it converts each element to tuple. It returns a zip object and hence it has to converted back to list using list(). 


Output
The original list : [1, 4, 6, 8, 9]
List after conversion to tuple list : [(1,), (4,), (6,), (8,), (9,)]

Method #3 : Using map()
In this method, we use the map() function to iterate through the original list and convert each integer element into a tuple object using a lambda function. The map() returns an iterable map object which is then converted to a list using the list() function. This method is also simple and easy to use.
 


Output
The original list : [1, 4, 6, 8, 9]
List after conversion to tuple list : [(1,), (4,), (6,), (8,), (9,)]

Time Complexity: O(n)
Auxiliary Space: O(n)

Comment