Python | Get sum of tuples having same first value
Last Updated :
23 Mar, 2023
Given a list of tuples, the task is to sum the tuples having the same first value.
Examples:
Input: [(1, 13), (2, 190), (3, 82), (1, 12)]
Output: [(1, 25), (2, 190), (3, 82)]
Input: [(1, 13), (1, 190), (3, 25), (1, 12)]
Output: [(1, 215), (3, 25)]
Let us discuss the different ways we can do this task.
Method #1: Using map()
Python3
# Python code to get sum of tuples having same first value
# Initialisation of list of tuple
Input = [(1, 13), (1, 190), (3, 25), (1, 12)]
d = {x: 0 for x, _ in Input}
for name, num in Input:
d[name] += num
# using map
Output = list(map(tuple, d.items()))
# printing output
print(Output)
Output:[(1, 215), (3, 25)]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using defaultdict
Python3
# Python code to sum list of tuples having same first value
# Importing
from collections import defaultdict
# Initialisation of list of tuple
Input = [(2, 190), (1, 13), (1, 12),
(2, 14), (3, 82), (1, 70)]
# Initialisation of defaultdict
output = defaultdict(int)
for k, v in Input:
output[k] += v
# Printing output
print(list(output.items()))
Output:[(1, 95), (2, 204), (3, 82)]
Time complexity: O(n), where n is the number of tuples in the Input list.
Auxiliary space: O(k), where k is the number of unique keys in the Input list.
Method #3: Using for loop
Python3
# Python code to get sum of tuples having same first value
# Initialisation of list of tuple
Input = [(1, 13), (1, 190), (3, 25), (1, 12)]
Output = []
x=[]
for i in Input:
if i[0] not in x:
x.append(i[0])
for i in x:
p=[]
p.append(i)
s=0
for j in Input:
if(j[0]==i):
s+=j[1]
p.append(s)
Output.append(tuple(p))
# printing output
print(Output)
Output[(1, 215), (3, 25)]
Time complexity: O(n^2) - nested loop over the input list
Auxiliary space: O(n) - creating a new list to store unique first values of tuples.
Method #4: Using a dictionary comprehension
Approach is using a dictionary comprehension to sum the tuples with the same first value. Here is an example of how this could be done:
Python3
def sum_tuples(input_list):
# Create a dictionary with the first values of the tuples as keys
# and the sum of the second values as values
sums = {key: sum(t[1] for t in input_list if t[0] == key) for key, _ in input_list}
# Return the dictionary as a list of tuples
return [(key, value) for key, value in sums.items()]
input_list = [(1, 13), (1, 190), (3, 25), (1, 12)]
print(sum_tuples(input_list)) # [(1, 215), (3, 25)]
#This code is contributed by Edula Vinay Kumar Reddy
Output[(1, 215), (3, 25)]
This approach first creates a dictionary with the first values of the tuples as keys and the sum of the second values as values. It then converts the dictionary back into a list of tuples using a dictionary comprehension. This method is relatively concise and easy to understand, and should be efficient for most cases. However, it may not be as efficient as some of the other methods mentioned in the article if you are working with extremely large lists of tuples.
Method #5:Using itertools groupby
- groupby() groups the input list by the first element of each tuple.
- The lambda function lambda x: x[0] is used as the key function to group by the first element of each tuple.
- sum(v for _, v in group) is used to compute the sum of values in each group.
- (k, sum(v for _, v in group)) is used to create new tuples with the first element being the key and the second element being the sum of values in each group.
- Input.sort(key=lambda x: x[0]) sorts the input list by the first element of each tuple, which is required by groupby().
Python3
from itertools import groupby
# Initialisation of list of tuple
Input = [(1, 13), (1, 190), (3, 25), (1, 12)]
# sorting the list by the first element of each tuple
Input.sort(key=lambda x: x[0])
# using groupby from itertools to group tuples by the first element
groups = groupby(Input, lambda x: x[0])
# computing the sum of values in each group and creating new tuples
output = [(k, sum(v for _, v in group)) for k, group in groups]
print(output)
#This code is contributed by Vinay Pinjala.
Output[(1, 215), (3, 25)]
The time complexity of this solution is O(n log n), where n is the number of tuples in the input list. This is because the first step of the algorithm sorts the list based on the first element of each tuple, which has a time complexity of O(n log n) in the average case.
The auxiliary space of this solution is O(n), where n is the number of tuples in the input list. This is because the algorithm needs to store a sorted version of the input list and a dictionary to keep track of the sum of values for each unique first value in the input list. The size of these data structures will be proportional to the size of the input list, which is O(n).
Method 6: Using the pandas library.
Step-by-step approach:
- Import the pandas library.
- Create a pandas dataframe from the input list of tuples.
- Use the groupby() method to group the dataframe by the first column.
- Use the sum() method to get the sum of each group.
- Convert the resulting dataframe back to a list of tuples.
Below is the implementation of the above approach:
Python3
import pandas as pd
Input = [(1, 13), (1, 190), (3, 25), (1, 12)]
# create dataframe from input list
df = pd.DataFrame(Input)
# group by the first column and get the sum of each group
grouped = df.groupby(0).sum()
# convert dataframe back to list of tuples
output = [tuple(x) for x in grouped.to_records()]
# print output
print(output)
Output:
[(1, 215), (3, 25)]
Time complexity: O(n log n), where n is the number of tuples in the input list, due to the use of groupby() which requires sorting the dataframe.
Auxiliary space: O(n) due to the creation of the dataframe.
Similar Reads
Get Unique Values from a List in Python
Getting unique values from a list in Python allows you to remove duplicates and work with distinct elements. For example, given the list a = [1, 2, 1, 1, 3, 4, 3, 3, 5], you might want to extract the unique values [1, 2, 3, 4, 5]. There are various efficient methods to extract unique values from a l
3 min read
Python | sort list of tuple based on sum
Given, a list of tuple, the task is to sort the list of tuples based on the sum of elements in the tuple. Examples: Input: [(4, 5), (2, 3), (6, 7), (2, 8)] Output: [(2, 3), (4, 5), (2, 8), (6, 7)] Input: [(3, 4), (7, 8), (6, 5)] Output: [(3, 4), (6, 5), (7, 8)] # Method 1: Using bubble sort Using th
4 min read
Python | Find whether all tuple have same length
Given a list of tuples, the task is to find whether all tuple have same length. Below are some ways to achieve the above task. Method #1: Using Iteration Python3 # Python code to find whether all # tuple have equal length # Input List initialization Input = [(11, 22, 33), (44, 55, 66)] # printing pr
6 min read
Create a List of Tuples in Python
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
How to Add Same Key Value in Dictionary Python
Dictionaries are powerful data structures that allow us to store key-value pairs. However, one common question that arises is how to handle the addition of values when the keys are the same. In this article, we will see different methods to add values for the same dictionary key using Python.Adding
2 min read
Position Summation in List of Tuples - Python
Position Summation in List of Tuples refers to the process of calculating the sum of elements at the same positions across multiple tuples in a list. This operation involves adding up the corresponding elements from each tuple.For example, consider the list of tuples [(1, 6), (3, 4), (5, 8)]. The go
3 min read
Python | Find the number of unique subsets with given sum in array
Given an array and a sum, find the count of unique subsets with each subset's sum equal to the given sum value. Examples: Input : 4 12 5 9 12 9 Output : 2 (subsets will be [4, 5] and [9]) Input : 1 2 3 4 5 10 Output : 3 We will use dynamic programming to solve this problem and this solution has time
2 min read
How to iterate through list of tuples in Python
In Python, a list of tuples is a common data structure used to store paired or grouped data. Iterating through this type of list involves accessing each tuple one by one and sometimes the elements within the tuple. Python provides several efficient and versatile ways to do this. Letâs explore these
2 min read
Python | Sort Tuples in Increasing Order by any key
Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples: Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : So
3 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