# Python – Tuple Matrix Columns Summation

Sometimes, while working with Tuple Matrix, we can have a problem in which we need to perform summation of each column of tuple matrix, at the element level. This kind of problem can have application in Data Science domains. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [[(4, 5), (1, 2)], [(2, 4), (4, 6)]]
Output : [(6, 9), (5, 8)]

Input : test_list = [[(4, 5), (1, 2), (6, 7)]]
Output : [(4, 5), (1, 2), (6, 7)]

Method #1 : Using list comprehension + zip() + sum() The combination of above functions can be used to solve this problem. In this, we perform the task of sum using sum() and zip() is used to perform column wise pairing of all elements.

step by step approach of the program:

1. Define a nested list test_list containing tuples of integers.
2. Print the original list.
3. Create a list comprehension to iterate over the columns of the matrix.
4. Use the zip() function to group the tuples in each column together.
5. Apply the sum() function to each group of tuples to get the sum of the elements in that column.
6. Wrap the result of the sum() function in a tuple using the tuple() constructor.
7. Append the tuple of column sums to the result list for each column.
8. Print the result list.

## Python3

 `# Python3 code to demonstrate working of ` `# Tuple Matrix Columns Summation` `# Using list comprehension + zip() + sum()`   `# initializing lists` `test_list ``=` `[[(``4``, ``5``), (``3``, ``2``)], [(``2``, ``2``), (``4``, ``6``)], [(``3``, ``2``), (``4``, ``5``)]]`   `# printing original list` `print``("The original ``list` `is` `: " ``+` `str``(test_list))`   `# Tuple Matrix Columns Summation` `# Using list comprehension + zip() + sum()` `res ``=` `[``tuple``(``sum``(ele) ``for` `ele ``in` `zip``(``*``i)) ``for` `i ``in` `zip``(``*``test_list)]`   `# printing result ` `print``("``Tuple` `matrix columns summation : " ``+` `str``(res))`

Output :

```The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
Tuple matrix columns summation : [(9, 9), (11, 13)]```

Time complexity: O(n^2) where n is the number of elements in the input list.
Auxiliary space: O(n^2) as well, where n is the number of elements in the input list.

Method #2 : Using map() + list comprehension + zip() The combination of above functions can be used to solve this problem. In this, we perform the task of extension of sum() using map() and rest of the functionalities are performed similar to above method.

## Python3

 `# Python3 code to demonstrate working of ` `# Tuple Matrix Columns Summation` `# Using map() + list comprehension + zip()`   `# initializing lists` `test_list ``=` `[[(``4``, ``5``), (``3``, ``2``)], [(``2``, ``2``), (``4``, ``6``)], [(``3``, ``2``), (``4``, ``5``)]]`   `# printing original list` `print``("The original ``list` `is` `: " ``+` `str``(test_list))`   `# Tuple Matrix Columns Summation` `# Using map() + list comprehension + zip()` `res ``=` `[``tuple``(``map``(``sum``, ``zip``(``*``ele))) ``for` `ele ``in` `zip``(``*``test_list)]`   `# printing result ` `print``("``Tuple` `matrix columns summation : " ``+` `str``(res))`

Output :

```The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
Tuple matrix columns summation : [(9, 9), (11, 13)]```

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.  map() + list comprehension + zip() performs n*n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list

Method #3: Using NumPy library

This program imports the NumPy library and converts a given matrix (test_list) into a NumPy array. It then calculates the column-wise sum of the array using the np.sum() function and returns the result as a tuple. Finally, it prints the tuple containing the column-wise sums of the matrix.

## Python3

 `import` `numpy as np`   `# initializing matrix` `test_list ``=` `[[(``4``, ``5``), (``3``, ``2``)], [(``2``, ``2``), (``4``, ``6``)], [(``3``, ``2``), (``4``, ``5``)]]`   `# converting matrix to NumPy array` `arr ``=` `np.array(test_list)`   `# calculating column-wise sum` `res ``=` `tuple``(``map``(``tuple``, np.``sum``(arr, axis``=``0``)))`   `# printing result` `print``(``"Tuple matrix columns summation : "` `+` `str``(res))`

OUTPUT:

`Tuple matrix columns summation : ((9, 9), (11, 13))`

The time complexity of the code snippet would be O(n^2), where n is the number of elements in the matrix.

The auxiliary space complexity of the code would be O(n^2) as well, because we are creating a NumPy array to store the matrix elements.

Method #4: Using a for loop and nested loops to iterate over the matrix and sum the columns.

In this method, we use a for loop to iterate over the columns of the matrix. For each column, we initialize a tuple col_sum with zeros, and then use nested loops to iterate over the rows and add the values in each row to col_sum. We use the zip() function to group the values in the same position in each row together, and the map() function to sum these values. Finally, we append col_sum to the result list.

Step-by-step approach:

• Initialize an empty result list res.
• Iterate over each column using a for loop with range() function and the number of columns num_cols.
• For each column, we initialize a tuple col_sum with zeros using (0, 0).
• Iterate over each row using a nested for loop with range() function and the number of rows num_rows.
• For each row, we use the zip() function to group the values in the same position in each row together, and the map() function to sum these values using the sum() function. We add these values to col_sum using the tuple() function to convert the result to a tuple.
• After iterating over all rows, we append col_sum to the result list res.
• After iterating over all columns, we have the required result stored in res.
• We print the result using the print() function and concatenation of string and the list.

Below is the implementation of the above approach:

## Python3

 `# Python3 code to demonstrate working of ` `# Tuple Matrix Columns Summation` `# Using for loop and nested loops`   `# initializing lists` `test_list ``=` `[[(``4``, ``5``), (``3``, ``2``)], [(``2``, ``2``), (``4``, ``6``)], [(``3``, ``2``), (``4``, ``5``)]]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# Tuple Matrix Columns Summation` `# Using for loop and nested loops` `num_rows ``=` `len``(test_list)` `num_cols ``=` `len``(test_list[``0``])` `res ``=` `[]` `for` `j ``in` `range``(num_cols):` `    ``col_sum ``=` `(``0``, ``0``)` `    ``for` `i ``in` `range``(num_rows):` `        ``col_sum ``=` `tuple``(``map``(``sum``, ``zip``(col_sum, test_list[i][j])))` `    ``res.append(col_sum)`   `# printing result ` `print``(``"Tuple matrix columns summation : "` `+` `str``(res))`

Output

```The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
Tuple matrix columns summation : [(9, 9), (11, 13)]```

The time complexity of this method is O(n^2), where n is the number of rows or columns in the matrix.
The auxiliary space complexity is O(n), since we need to store the result list.

Method #5: Using itertools module

Uses the itertools module to iterate over the columns of the matrix and sum them.

Step-by-step approach:

• Import the itertools module.
• Initialize an empty list to store the column sums.
• Iterate over the columns of the matrix using the zip() function and the * operator to unpack the tuples.
• Use the sum() function to calculate the sum of each column and append it to the list of column sums.
• Convert the list of column sums to a tuple and print it as the result.

## Python3

 `import` `itertools`   `# initializing matrix` `test_list ``=` `[[(``4``, ``5``), (``3``, ``2``)], [(``2``, ``2``), (``4``, ``6``)], [(``3``, ``2``), (``4``, ``5``)]]`   `# calculating column-wise sum using itertools` `col_sums ``=` `[]` `for` `col ``in` `itertools.zip_longest(``*``test_list, fillvalue``=``(``0``, ``0``)):` `    ``col_sum ``=` `sum``([x[``0``] ``for` `x ``in` `col]), ``sum``([x[``1``] ``for` `x ``in` `col])` `    ``col_sums.append(col_sum)`   `# converting column sums to tuple` `res ``=` `tuple``(col_sums)`   `# printing result` `print``(``"Tuple matrix columns summation : "` `+` `str``(res))`

Output

`Tuple matrix columns summation : ((9, 9), (11, 13))`

Time complexity: O(nm), where n is the number of rows and m is the number of columns in the matrix.
Auxiliary space: O(m), where m is the number of columns in the matrix.

Method 6: Using reduce() function from the functools module and lambda function

1. Import the reduce() function from the functools module.
2. Initialize the test_list with a nested list of tuples.
3. Print the original list using the print() function.
4. Use the zip() function to group the tuples from the same column of the matrix together.
5. Use a list comprehension to iterate over the zipped list of columns and apply the reduce() function with a lambda function that takes two tuples and adds their corresponding elements.
6. Convert the resulting tuple back to a tuple and append it to the res list using tuple comprehension.
7. Print the res list containing the sum of columns of the matrix.

## Python3

 `# Python3 code to demonstrate working of` `# Tuple Matrix Columns Summation` `# Using reduce() and lambda`   `from` `functools ``import` `reduce`   `# initializing lists` `test_list ``=` `[[(``4``, ``5``), (``3``, ``2``)], [(``2``, ``2``), (``4``, ``6``)], [(``3``, ``2``), (``4``, ``5``)]]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# Tuple Matrix Columns Summation` `# Using reduce() and lambda` `res ``=` `[``tuple``(``reduce``(``lambda` `x, y: (x[``0``]``+``y[``0``], x[``1``]``+``y[``1``]), i))` `       ``for` `i ``in` `zip``(``*``test_list)]`   `# printing result` `print``(``"Tuple matrix columns summation : "` `+` `str``(res))`

Output

```The original list is : [[(4, 5), (3, 2)], [(2, 2), (4, 6)], [(3, 2), (4, 5)]]
Tuple matrix columns summation : [(9, 9), (11, 13)]```

The time complexity is O(mn), where m is the number of rows and n is the number of columns in the matrix.

The space complexity is O(n), where n is the number of columns in the matrix.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next