Python | Mean of tuple list
Sometimes, while working with Python tuple list, we can have a problem in which we need to find the average of tuple values in the list. This problem has the possible application in many domains including mathematics. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loops
The first approach that can be thought of to solve this problem can be a brute force approach in which we just loop each tuple to add element and then just divide it by number of tuples in the list.
# Python3 code to demonstrate working of # Mean of tuple list # Using loops # Initializing list test_list = [(1, 4, 5), (7, 8), (2, 4, 10)] # printing original list print("The original list is : " + str(test_list)) # Average of tuple list # Using loops sum = 0for sub in test_list: for i in sub: sum = sum + i res = sum / len(test_list) # printing result print("The mean of tuple list is : " + str(res)) |
The original list is : [(1, 4, 5), (7, 8), (2, 4, 10)] The mean of tuple list is : 13.666666666666666
Method #2 : Using chain() + sum()
In order to reduce the line of codes, the chain() functionality can be used so that all the elements can be extracted and then can be added using sum().
# Python3 code to demonstrate working of # Mean of tuple list # Using chain() + sum() from itertools import chain # Initializing list test_list = [(1, 4, 5), (7, 8), (2, 4, 10)] # printing original list print("The original list is : " + str(test_list)) # Average of tuple list # Using chain() + sum() temp = list(chain(*test_list)) res = sum(temp)/ len(test_list) # printing result print("The mean of tuple list is : " + str(res)) |
The original list is : [(1, 4, 5), (7, 8), (2, 4, 10)] The mean of tuple list is : 13.666666666666666
Recommended Posts:
- Python | Sort tuple list by Nth element of tuple
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Merge list of tuple into list by joining the strings
- Python | Pair and combine nested list to tuple list
- Python | Convert list to indexed tuple list
- Python | Convert Integral list to tuple list
- Python | Convert a list into a tuple
- Python | Add tuple to front of list
- Python | Difference Between List and Tuple
- Python | Group tuple into list based on value
- Python | Join tuple elements in a list
- Python | Convert a list into tuple of lists
- Python | Dictionary to list of tuple conversion
- Python | Convert list of tuple into dictionary
- Python | Summation of Kth Column of Tuple List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



