![]() |
VOOZH | about |
Sometimes, while working with Python tuples, we can have a problem in which we need to perform tuple transpose of elements i.e, each column element of dual tuple becomes a row, a 2*N Tuple becomes N * 2 Tuple List. This kind of problem can have possible applications in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be performed.
Input : test_list = [(2, 'Gfg'), (3, 'is'), (94, 'Best')] Output : ([2, 3, 94], ['Gfg', 'is', 'Best']) Input : test_list = [(8, 1)] Output : ([8, 1])
Method #1: Using loop
This is one of the ways in which this problem can be solved. In this, we employ a brute force strategy to perform the transpose by constructing 2 lists and combining them to get the transposed results.
Output:
The original list is : [(5, 1), (3, 4), (9, 7), (10, 6)] The transposed tuple list : ([5, 3, 9, 10], [1, 4, 7, 6])
Time complexity: O(N), where N is the length of the input list. This is because the program iterates through each element of the input list once in the for loop.
Auxiliary space: O(N), where N is the length of the input list. This is because the program creates two new lists, sub1 and sub2, each of size N, to store the transposed elements of the input list.
Method #2 : Using loop + zip() + tuple()
The combination of above functionalities can also be used to solve this problem. In this, we perform the task of forming transpose and extract columnar elements using zip().
Output:
The original list is : [(5, 1), (3, 4), (9, 7), (10, 6)] The transposed tuple list : ([5, 3, 9, 10], [1, 4, 7, 6]
Time complexity: O(n), where n is the number of tuples in the input list.
Auxiliary space: O(n), where n is the number of tuples in the input list.
Method #3: Using the numpy library:
Step-by-step approach:
Output:
The original list is : [(5, 1), (3, 4), (9, 7), (10, 6)] The transposed tuple list : [(5, 3, 9, 10), (1, 4, 7, 6)]
Time complexity: O(n^2), where n is the length of the input list of tuples.
Auxiliary Space: O(n), where n is the length of the input list of tuples.
Method #4: Using list comprehension and map() function
Step-by-step approach:
The original list is: [(5, 1), (3, 4), (9, 7), (10, 6)] The transposed tuple list is: [[5, 3, 9, 10], [1, 4, 7, 6]]
Time complexity: O(n^2) due to the nested iteration of zip() and map().
Auxiliary space: O(n) for the transposed list that is created.