Open In App
Related Articles

Python | Summation of Kth Column of Tuple List

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using list comprehension + sum() 

This task can be performed using the combination of above functionalities. In this, summation of index occurs using sum() and list comprehension drives the iteration and access of Nth index element of each tuple in list. 

Python3

# Python3 code to demonstrate working of
# Summation of Kth Column of Tuple List
# using list comprehension + sum()
 
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Summation of Kth Column of Tuple List
# using list comprehension + sum()
res = sum([sub[K] for sub in test_list])
 
# printing result
print("Summation of Kth Column of Tuple List : " + str(res))

                    

Output
The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Summation of Kth Column of Tuple List : 31

Time Complexity: O(n), where n is the number of Tuples in given list.
Auxiliary Space: O(n)

Method #2: Using imap() + sum() + itemgetter()

 The combination of above functions can also achieve this task. This approach is generator based and recommended in case we have a very large list. In this, sum() is used to perform summation, itemgetter to get Kth index and imap() performs the task of mapping elements to perform summation. Works only in Python2. 

Python

# Python code to demonstrate working of
# Summation of Kth Column of Tuple List
# using imap() + sum() + itemgetter()
from operator import itemgetter
from itertools import imap
 
# initialize list
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Summation of Kth Column of Tuple List
# using imap() + sum() + itemgetter()
idx = itemgetter(K)
res = sum(imap(idx, test_list))
 
# printing result
print("Summation of Kth Column of Tuple List : " + str(res))

                    

Output
The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Summation of Kth Column of Tuple List : 31

Time complexity: O(n), where n is the number of tuples in the list. 
Auxiliary space: O(1), because the amount of extra memory used by the algorithm is constant, regardless of the size of the input. 

Method #3: Using numpy

Note: Install numpy module using command “pip install numpy”

Another approach to solve this problem is by using the numpy library. This can be done by converting the tuple list into a numpy array and then using numpy’s sum() function along with the index of the desired column.

Python3

import numpy as np
 
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize K
K = 2
 
# Summation of Kth Column of Tuple List
# using numpy
res = np.sum(np.array(test_list)[:,K])
 
# printing result
print("Summation of Kth Column of Tuple List : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy

                    

Output:

The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Summation of Kth Column of Tuple List : 31

Time complexity: O(n) where n is the number of tuples in the list. It iterates through the list once to extract the values of the kth index. 
Auxiliary space: O(n) as well, as it creates a new numpy array with n elements to store the kth index values.

Method #4: Using a for loop

  • Initialize the list of tuples
  • Print the original list
  • Initialize the value of K
  • Initialize the sum to zero
  • Iterate over each tuple in the list
    • Add the Kth element of the current tuple to the sum
  • Print the result

Python3

# initialize the list of tuples
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# print the original list
print("The original list is : " + str(test_list))
 
# initialize the value of K
K = 2
 
# initialize the sum to zero
res = 0
 
# iterate over each tuple in the list
for tup in test_list:
    # add the Kth element of the current tuple to the sum
    res += tup[K]
 
# print the result
print("Summation of Kth Column of Tuple List : " + str(res))

                    

Output
The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Summation of Kth Column of Tuple List : 31

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(1).

Method #5: Using Recursive method.

Algorithm:

  1. Define a recursive function sum_kth_column_recursive that takes two arguments: tuples_list and k.
  2. If tuples_list is empty, return 0 (base case).
  3. Otherwise, add the Kth element of the first tuple in tuples_list to the sum, and call the function recursively with the rest of the list (recursive case).
  4. Return the final sum.

Python3

def sum_kth_column_recursive(tuples_list, k):
    # base case: empty list
    if not tuples_list:
        return 0
     
    # recursive case: add the Kth element of the first tuple to the sum,
    # and call the function recursively with the rest of the list
    return tuples_list[0][k] + sum_kth_column_recursive(tuples_list[1:], k)
 
# initialize the list of tuples
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# print the original list
print("The original list is : " + str(test_list))
 
# initialize the value of K
K = 2
 
# initialize the sum to zero
res = sum_kth_column_recursive(test_list,K)
 
# print the result
print("Summation of Kth Column of Tuple List : " + str(res))

                    

Output
The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Summation of Kth Column of Tuple List : 31

Time complexity: O(n), where n is the number of tuples in the list. In the worst case, we will need to traverse the entire list to compute the sum.
Auxiliary Space: O(n), where n is the number of tuples in the list. The space used by the recursive function call stack will be proportional to the number of tuples in the list.

Method 6: Using the built-in function reduce() from the functools module.

Step-by-step approach:

  • The reduce() function from the functools module is used to apply a function to each tuple in the list, accumulating the sum of the k-th element so far.
  • The function passed to reduce() takes two arguments: acc, which is the accumulated sum so far, and tpl, which is the current tuple being processed.
  • The lambda function returns the sum of the accumulated sum so far (acc) and the k-th element of the current tuple (tpl[k]).
  • The reduce() function starts with an initial value of 0 for the accumulated sum.
  • The test_list variable initializes a list of tuples that will be used to test the sum_kth_column_reduce function.
  • The K variable initializes the value of the index of the column to sum.
  • The res variable initializes the sum to zero using the sum_kth_column_reduce function with test_list and K as arguments.
  • The print() function is used to output the original list of tuples and the sum of the k-th column.

Below is the implementation of the above approach:

Python3

import functools
 
def sum_kth_column_reduce(tuples_list, k):
    return functools.reduce(lambda acc, tpl: acc + tpl[k], tuples_list, 0)
 
# initialize the list of tuples
test_list = [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
 
# initialize the value of K
K = 2
 
# initialize the sum to zero
res = sum_kth_column_reduce(test_list, K)
 
# print the original list
print("The original list is : " + str(test_list))
 
# print the result
print("Summation of Kth Column of Tuple List : " + str(res))

                    

Output
The original list is : [(5, 6, 7), (1, 3, 5), (8, 9, 19)]
Summation of Kth Column of Tuple List : 31

Time complexity: O(n), where n is the length of the input tuples_list. 
Auxiliary space: O(1), as the program only uses a constant amount of additional memory, regardless of the size of the input.



Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads