w3resource

Python: Calculate the average value of the numbers in a given tuple of tuples using lambda


44. Average Tuple of Tuples Lambda

Write a Python program to calculate the average value of the numbers in a given tuple of tuples using lambda.

Sample Solution:

Python Code :

# Define a function 'average_tuple' that calculates the average of elements in a tuple of tuples
def average_tuple(nums):
    # Use 'zip(*nums)' to unpack the tuples in 'nums' and then apply 'map' with a lambda to calculate the averages
    # For each position (index) in the unpacked tuples, calculate the average of elements at that position across tuples
    # Convert the averages into a tuple
    result = tuple(map(lambda x: sum(x) / float(len(x)), zip(*nums)))
    
    # Return the tuple of average values
    return result

# Create a tuple of tuples 'nums' containing integer values
nums = ((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))

# Print the original tuple 'nums' and the average value of numbers in the tuple of tuples using 'average_tuple' function
print("Original Tuple:")
print(nums)
print("\nAverage value of the numbers of the said tuple of tuples:\n", average_tuple(nums))

# Create another tuple of tuples 'nums' containing integer values including negative numbers
nums = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))

# Print the original tuple 'nums' and the average value of numbers in the tuple of tuples using 'average_tuple' function
print("\nOriginal Tuple:")
print(nums)
print("\nAverage value of the numbers of the said tuple of tuples:\n", average_tuple(nums)) 

Sample Output:

Original Tuple: 
((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))

Average value of the numbers of the said tuple of tuples:
 (30.5, 34.25, 27.0)

Original Tuple: 
((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))

Average value of the numbers of the said tuple of tuples:
 (25.5, -18.0, 3.75)

For more Practice: Solve these Related Problems:

  • Write a Python program to calculate the median of numbers in a tuple of tuples using lambda.
  • Write a Python program to compute the average value for each inner tuple separately using lambda.
  • Write a Python program to calculate the weighted average of numbers in a tuple of tuples using lambda.
  • Write a Python program to calculate the average value of numbers in a tuple of tuples, excluding the highest and lowest values in each inner tuple, using lambda.

Go to:


Previous: Write a Python program to multiply all the numbers in a given list using lambda.
Next: Write a Python program to convert string element to integer inside a given tuple using lambda.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.