![]() |
VOOZH | about |
Sometimes, while working with Python tuple, we can have a problem in which we need to compute average of any particular index of tuples in a list. This kind of problem can have application in data domain such as web development. Let's discuss certain ways in which this task can be performed.
Input : test_list = [('Gfg', 1), ('is', 5), ('best', 7)], K = 1
Output : 4.333333333333333Input : test_list = [('Gfg', 7), ('best', 7)], K = 1
Output : 7
Method #1: Using mean() + generator expression
The combination of above functions can be used to solve this problem. In this, we perform the task of mean computation using mean() and generator expression is used for iterations.
The original list is : [('Gfg', 4), ('is', 18), ('best', 2), ('for', 5), ('geeks', 1)]
The computed mean : 6Time complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(1), the space used is constant irrespective of the input size.
Method #2 : Using sum() + len() + generator expression
The combination of above functions can also be employed to solve this task. In this, we perform task of summation computation using sum() and result is divided by list length computed using len().
The original list is : [('Gfg', 4), ('is', 18), ('best', 2), ('for', 5), ('geeks', 1)]
The computed mean : 6.0Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1) here constant space is required
Method #3: Using reduce
This code uses the reduce() function from the functools module to compute the sum of the second element of each tuple in the list. It then divides the sum by the length of the list to compute the mean of the second element of the tuples in the list.
The original list is : [('Gfg', 4), ('is', 18), ('best', 2), ('for', 5), ('geeks', 1)]
The computed mean : 6.0Time complexity: O(n), where n is the length of the input list. This is because the reduce() function iterates through the list once to compute the sum of the second element of the tuples, and then the final division operation takes constant time.
Auxiliary space: O(1), because it only uses a constant amount of extra space to store the sum and the length of the list.
Method #4: Using a loop
Step-by-step approach:
The original list is : [('Gfg', 4), ('is', 18), ('best', 2), ('for', 5), ('geeks', 1)]
The computed mean : 6.0Time complexity: O(n), where n is the length of test_list.
Auxiliary space: O(1).
Method #5: Using numpy.mean()
Output:
The original list is : [('Gfg', 4), ('is', 18), ('best', 2), ('for', 5), ('geeks', 1)]
The computed mean : 6.0
Time complexity: O(n), where n is the length of the input list
Auxiliary space: O(n), where n is the length of the input list (to store the kth index list)