In this article, we will discuss how to convert a List of tuples to multiple lists. We can convert list of tuples to multiple lists by using the map() function
Syntax: map(list, zip(*list_of_tuples)
Example:
Input: [('a', 'b', 'c'), (1,2,3), ('1','3','4')] Output: ['a', 'b', 'c'], [1, 2, 3], ('1', '3', '4')
Example 1: Python code to display a list of tuples and display them.
Python3
# list of tuple for student data # with both integer and strings a = [( 1 , 2 , 3 , 4 , 5 ), ( "sravan" , "bobby" , "ojaswi" , "rohith" , "Gnanesh" ), ( 96 , 89 , 78 , 90 , 78 )] # display print ( "Original list of tuple" ) print (a) # list of tuple for student data # with both integer and strings a = [( 1 , 2 , 3 , 4 , 5 ), ( "sravan" , "bobby" , "ojaswi" , "rohith" , "Gnanesh" ), ( 96 , 89 , 78 , 90 , 78 )] # convert list of tuple to multiple lists data = map ( list , zip ( * a)) print ("") # display print ( "List" ) for i in data: print (i) |
Output:
Original list of tuple
[(1, 2, 3, 4, 5), (‘sravan’, ‘bobby’, ‘ojaswi’, ‘rohith’, ‘Gnanesh’), (96, 89, 78, 90, 78)]
List
[1, ‘sravan’, 96]
[2, ‘bobby’, 89]
[3, ‘ojaswi’, 78]
[4, ‘rohith’, 90]
[5, ‘Gnanesh’, 78]
Time complexity: O(n), where n is the length of the original list of tuples.
Auxiliary space: O(n), as we create a new list of lists with the same number of elements as the original list of tuples.
Example 2: Python code to convert a list of tuples to multiple lists
Python3
# list of tuple for student # data with both integer and strings a = [( 1 , 2 , 3 , 4 , 5 ), ( "sravan" , "bobby" , "ojaswi" , "rohith" , "Gnanesh" ), ( 96 , 89 , 78 , 90 , 78 ), ( "kakumanu" , "kakumanu" , "hyd" , "hyd" , "hyd" )] # convert list of tuple to multiple lists data = map ( list , zip ( * a)) # display for i in data: print (i) |
Output:
[1, 'sravan', 96, 'kakumanu'] [2, 'bobby', 89, 'kakumanu'] [3, 'ojaswi', 78, 'hyd'] [4, 'rohith', 90, 'hyd'] [5, 'Gnanesh', 78, 'hyd']
Method 3 using numpy
This code uses the numpy library to convert the list of tuples to a numpy array, transpose it, and then convert it back to a list. Finally, it prints out each element of the resulting list.
Python3
import numpy as np # list of tuple for student data # with both integer and strings a = [( 1 , 2 , 3 , 4 , 5 ), ( "sravan" , "bobby" , "ojaswi" , "rohith" , "Gnanesh" ), ( 96 , 89 , 78 , 90 , 78 ), ( "kakumanu" , "kakumanu" , "hyd" , "hyd" , "hyd" )] # convert list of tuple to numpy array data = np.array(a).T.tolist() # display for i in data: print (i) |
OUTPUT: ['1', 'sravan', '96', 'kakumanu'] ['2', 'bobby', '89', 'kakumanu'] ['3', 'ojaswi', '78', 'hyd'] ['4', 'rohith', '90', 'hyd'] ['5', 'Gnanesh', '78', 'hyd']
The time complexity of the np.array() function in numpy is O(n) where n is the number of elements in the input list.
The space complexity of the code is O(n) as well.