Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Position Summation in List of Tuples

Python | Position Summation in List of Tuples

Sometimes the data that we receive is in the form of tuples having data from various sources and we can usually have a use case in which we require to process the sum of each index of tuple for cumulation. Let’s discuss certain ways in which this can be performed. 

Method #1: Using list comprehension 

This is the most naive method to perform this particular task, in this method, we compute the summation of each index of all the possible indices of the tuple.

Follow the below steps to implement the above idea:

  1. Create a list of tuples named “test_list” containing given tuples.
  2. Print the original list using the “print” function and string concatenation.
  3. Use a list comprehension to perform the position summation in the list of tuples. The “sum” function is used to add up the values in each position of the tuples. The result is stored in the variable “res“, which is a tuple containing two values.
  4. Print the position summation of the tuples using the “print” function and string concatenation.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# position summation in list of tuples
# using list comprehension
 
# initializing list
test_list = [(1, 6), (3, 4), (5, 8)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# position Summation in List of Tuples
# using list comprehension
res = sum(i[0] for i in test_list), sum(i[1] for i in test_list)
 
# printing summation
print("The position summation of tuples : " + str(res))


Output :

The original list is : [(1, 6), (3, 4), (5, 8)]
The position summation of tuples  : (9, 18)

Time complexity: O(n), where n is the number of tuples in the list. The list comprehension iterates through each tuple in the list once.
Auxiliary space: O(1), as only a constant amount of space is used for variables such as test_list, res, and the print statements. 

Method #2: Using zip() + sum() 

This is the most elegant and Pythonic way to perform this particular task. In this, we combine all the indices of the element using zip() and the performance of summation using sum function. 

Python3




# Python3 code to demonstrate
# position summation in list of tuples
# using zip() + sum()
 
# Initializing list
test_list = [(1, 6), (3, 4), (5, 8)]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Position Summation in List of Tuples
# using zip() + sum()
res = [sum(i) for i in zip(*test_list)]
 
# Printing summation
print("The position summation of tuples : " + str(res))


Output

The original list is : [(1, 6), (3, 4), (5, 8)]
The position summation of tuples : [9, 18]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), since only a few variables are used to store the input and output lists.

Method 3: Using loop

Use a loop to iterate through each tuple in the list and adds up the values at the first and second positions of each tuple. The sums are then combined into a tuple and printed as the result.

Python3




# Python3 code to demonstrate
# position summation in list of tuples
# using loop
 
# Initializing list
test_list = [(1, 6), (3, 4), (5, 8)]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Position Summation in List of Tuples
# using loop
 
sum_1 = 0
sum_2 = 0
 
for i in test_list:
    sum_1 += i[0]
    sum_2 += i[1]
     
res = (sum_1, sum_2)
 
# Printing summation
print("The position summation of tuples : " + str(res))


Output

The original list is : [(1, 6), (3, 4), (5, 8)]
The position summation of tuples  : (9, 18)

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), since only a few variables are used to store the input and output lists.

Method #4: Using the built-in function map() and sum()

This program calculates the sum of the first and second elements of each tuple in the input list test_list using map() and sum() functions and then stores the results in the variables sum_1 and sum_2. Finally, it stores the tuple (sum_1, sum_2) in the variable res and prints it.

Python3




# Custom input list
test_list = [(1, 6), (3, 4), (5, 8)]
 
# Position the summation in List of Tuples using map() and sum()
sum_1 = sum(map(lambda x: x[0], test_list))
sum_2 = sum(map(lambda x: x[1], test_list))
res = (sum_1, sum_2)
 
# Printing the summation
print("The position summation of tuples  : " + str(res))


Output

The position summation of tuples  : (9, 18)

Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(1) since we are only using a constant amount of extra space to store the variables sum_1, sum_2, and res

Method #5: Using Numpy

This code first converts the list of tuples to a numpy array using the np.array() function. It then uses numpy’s sum() function to compute the position summation along the columns (i.e., axis=0). The result is a numpy array, so we convert it back to a tuple using the tuple() function before printing.

Python3




import numpy as np
 
# Initializing list
test_list = [(1, 6), (3, 4), (5, 8)]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Convert list of tuples to numpy array
arr = np.array(test_list)
 
# Computing position summation using numpy's sum() function
res = np.sum(arr, axis=0)
 
# Printing the result
print("The position summation of tuples : " + str(tuple(res)))


Output: 

The original list is : [(1, 6), (3, 4), (5, 8)]
The position summation of tuples : (9, 18)

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(n), since we are creating a numpy array to store the input list of tuples.

Method 6: Using unpacking + built-in sum()

Approach:

  1. Define a function named tuple_sum that takes one argument tuple_list.
  2. Inside the function, use the unpacking operator (*) to separate the tuples into separate lists of the first and second elements.
  3. Use the built-in sum() function to calculate the sum of the first and second lists separately.
  4. Create a tuple of the two sums and return it.
  5. Call the function tuple_sum() with the test_list as an argument.
  6. Print the result.

Below is the implementation of the above approach:

Python3




def tuple_sum(tuple_list):
   
    first, second = zip(*tuple_list)
     
    return (sum(first), sum(second))
 
   
test_list = [(1, 6), (3, 4), (5, 8)]
result = tuple_sum(test_list)
print("The position summation of tuples: " + str(result))


Output

The position summation of tuples: (9, 18)

Time complexity: O(n)
Auxiliary space: O(n) (for the first and second lists created inside the function)

Method #7: Using map and lambda function + reduce() function

Here is the algorithm and code for the approach “Using map and lambda function with reduce”:

Algorithm:

  1. Initialize the list of tuples to “lst”.
  2. Import “functools” module to use the reduce function.
  3. Using the zip() function to group the tuples based on their positions.
  4. Applying reduce() on each group of tuples to get the sum of the numbers at each position.
  5. Using map() to apply the lambda function to each group.
  6. Converting the map object to a list to get the result.

Python3




import functools
 
# initializing list
lst = [(1, 6), (3, 4), (5, 8)]
 
# printing original list
print("The original list is : " + str(lst))
 
# Position Summation in List of Tuples using map and lambda function with reduce
res = list(map(lambda x: functools.reduce(lambda a,b: a+b, x), zip(*lst)))
 
# printing summation
print("The position summation of tuples  : " + str(tuple(res)))


Output

The original list is : [(1, 6), (3, 4), (5, 8)]
The position summation of tuples  : (9, 18)

Time complexity: O(N*M), where n is the number of tuples in the list and m is the length of each tuple.
The reduce function iterates through each tuple in the list once, and the map function iterates through each group of tuples once.
Auxiliary space: O(M), as only a list of size m is created to store the result.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments