Python | Average from a list of tuples



Method # 1: Using Loops
The first approach that can be used to solve this problem is — this is a brute force method where we just loop over each tuple to add an element and then just divide it by the number of tuples in the list.

Output:

 The original list is: [(1, 4, 5), (7, 8), (2, 4, 10)] The mean of tuple list is: 13.666666666666666 

Method number 2: And Using chain () + sum ()
To reduce the number of lines of code, you can use the chain () functionality to retrieve all the elements, and then add them with sum () .

# Python3 demo code work
# Average from the list of tuples
# Using loops

 
# Initializing list

test_list = [( 1 , 4 , 5 ), ( 7 , 8 ), ( 2 , 4 , 10 )]

 
# print the original list

print ( "The original list is:" + str (test_list))

 
# Average from the list of tuples
# Usage loops

sum = 0

for sub in test_list:

for i in sub:

sum = sum + i

res = sum / len (test_list)

 
# print result

print ( "The mean of tuple list is:" + str (res))

Output:

 The original list is: [(1, 4, 5), (7, 8), (2, 4, 10)] The mean of tuple list is: 13.666666666666666 

# Python3 code to demonstrate how it works
# Average from the list of tuples
# Using chain () + sum ()

from itertools import chain

 
# Initializing list

test_list = [( 1 , 4 < code class = "plain">, 5 ), ( 7 , 8 ), ( 2 , 4 , 10 )]

 
# print original list

print ( "The original list is:" + str ( test_list))

 
# Average from the list of tuples
# Using chain () + sum ()

temp = list (chain ( * test_list)) 

res = sum ( temp) / len (test_list)

 
# print result

print ( "The mean of tuple list is:" + str (res))