Transpose Dual Tuple List in Python
Last Updated :
03 May, 2023
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.
Python3
def hlper_fnc(test_list):
sub1 = []
sub2 = []
res = (sub1, sub2)
for sub in test_list:
sub1.append(sub[ 0 ])
sub2.append(sub[ 1 ])
return res
test_list = [( 5 , 1 ), ( 3 , 4 ), ( 9 , 7 ), ( 10 , 6 )]
print ( "The original list is : " + str (test_list))
res = hlper_fnc(test_list)
print ( "The transposed tuple list : " + str (res))
|
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().
Python3
def hlper_fnc(test_list):
return tuple ( zip ( * test_list))
test_list = [( 5 , 1 ), ( 3 , 4 ), ( 9 , 7 ), ( 10 , 6 )]
print ( "The original list is : " + str (test_list))
sub1, sub2 = hlper_fnc(test_list)
res = ( list (sub1), list (sub2))
print ( "The transposed tuple list : " + str (res))
|
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:
- Import the numpy library.
- Define the list of tuples to transpose.
- Convert the list of tuples to a numpy array using np.array().
- Use the transpose() function to transpose the array.
- Convert the transposed array back to a list of tuples using a list comprehension.
- Print the original list and the transposed tuple list.
Python3
import numpy as np
test_list = [( 5 , 1 ), ( 3 , 4 ), ( 9 , 7 ), ( 10 , 6 )]
arr = np.array(test_list)
res = arr.transpose()
print ( "The original list is : " + str (test_list))
print ( "The transposed tuple list : " + str ([ tuple (x) for x in res]))
|
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:
- A list of tuples called “test_list” is defined with 4 tuples containing 2 elements each.
- The “map” function is used in combination with a list comprehension to transpose the “test_list” by using the “zip” function to group together the first elements of each tuple, and the second elements of each tuple, respectively. This results in a new list of 2 tuples, each containing 4 elements.
- The “list” function is used to convert the result of the “map” function into a list, and this list is stored in the variable “transposed_list”.
- The original “test_list” and the transposed “transposed_list” are printed to the console using the “print” function and string concatenation. The original list is printed by converting it to a string using the “str” function.
Python3
test_list = [( 5 , 1 ), ( 3 , 4 ), ( 9 , 7 ), ( 10 , 6 )]
transposed_list = list ( map ( list , zip ( * test_list)))
print ( "The original list is: " + str (test_list))
print ( "The transposed tuple list is: " + str (transposed_list))
|
Output
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.
Similar Reads
range() to a list in Python
In Python, the range() function is used to generate a sequence of numbers. However, it produces a range object, which is an iterable but not a list. If we need to manipulate or access the numbers as a list, we must explicitly convert the range object into a list. For example, given range(1, 5), we m
2 min read
Convert Tuple to List in Python
In Python, tuples and lists are commonly used data structures, but they have different properties: Tuples are immutable: their elements cannot be changed after creation.Lists are mutable: they support adding, removing, or changing elements.Sometimes, you may need to convert a tuple to a list for fur
2 min read
Python | Linear search on list or tuples
Let us see a basic linear search operation on Python lists and tuples. A simple approach is to do a linear search, that is Start from the leftmost element of the list and one by one compare x with each element of the list.If x matches with an element, return True.If x doesnât match with any of the e
2 min read
Python | Remove empty tuples from a list
The task of removing empty tuples from a list in Python involves filtering out tuples that contain no elements i.e empty. For example, given a list like [(1, 2), (), (3, 4), (), (5,)], the goal is to remove the empty tuples () and return a new list containing only non-empty tuples: [(1, 2), (3, 4),
3 min read
Python | Set 3 (Strings, Lists, Tuples, Iterations)
In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quo
3 min read
Convert List Of Tuples To Json Python
Working with data often involves converting between different formats, and JSON is a popular choice for data interchange due to its simplicity and readability. In Python, converting a list of tuples to JSON can be achieved through various approaches. In this article, we'll explore four different met
3 min read
Transpose a matrix in Single line in Python
Transpose of a matrix is a task we all can perform very easily in Python (Using a nested loop). But there are some interesting ways to do the same in a single line. In Python, we can implement a matrix as a nested list (a list inside a list). Each element is treated as a row of the matrix. For examp
4 min read
How to Take a Tuple as an Input in Python?
Tuples are immutable data structures in Python making them ideal for storing fixed collections of items. In many situations, you may need to take a tuple as input from the user. Let's explore different methods to input tuples in Python. The simplest way to take a tuple as input is by using the split
3 min read
Python - Create a List of Tuples
The task of creating a list of tuples in Python involves combining or transforming multiple data elements into a sequence of tuples within a list. Tuples are immutable, making them useful when storing fixed pairs or groups of values, while lists offer flexibility for dynamic collections. For example
3 min read
Ways to Iterate Tuple List of Lists - Python
In this article we will explore different methods to iterate through a tuple list of lists in Python and flatten the list into a single list. Basically, a tuple list of lists refers to a list where each element is a tuple containing sublists and the goal is to access all elements in a way that combi
3 min read