w3resource

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

Python Lambda: Exercise-44 with Solution

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

Sample Solution:

Python Code :

def average_tuple(nums):
    result = tuple(map(lambda x: sum(x) / float(len(x)), zip(*nums)))
    return result

nums = ((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))
print ("Original Tuple: ")
print(nums)
print("\nAverage value of the numbers of the said tuple of tuples:\n",average_tuple(nums))
nums = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
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)

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

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

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.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

Python: Tips of the Day

Memoization using LRU cache:

import functools

@functools.lru_cache(maxsize=128)
def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    return fibonacci(n - 1) + fibonacci(n - 2)