Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to find sum and average of a list - Python Program

Example 1 :

def sum_and_average(lst): """Return sum and average.""" return sum(lst), sum(lst)/len(lst) print(sum_and_average([10, 20, 30]))

Output

 
OUTPUT  :
(60, 20.0)

Example 2 :

def calculate_sum_and_average(numbers_list): """ Calculates the sum and average of a list of numbers. Args: numbers_list (list): A list containing numeric values. Returns: tuple: A tuple containing the sum and the average of the list. Returns (0, 0) if the list is empty to avoid division by zero. """ if not numbers_list: # Handle empty list case return 0, 0 total_sum = sum(numbers_list) total_count = len(numbers_list) average = total_sum / total_count return total_sum, average # Example Usage and Output: my_list = [10, 20, 30, 40, 50] list_sum, list_average = calculate_sum_and_average(my_list) print(f"Original List: {my_list}") print(f"Sum of the list: {list_sum}") print(f"Average of the list: {list_average}") # Example with an empty list empty_list = [] empty_sum, empty_average = calculate_sum_and_average(empty_list) print(f"\nOriginal List (Empty): {empty_list}") print(f"Sum of the empty list: {empty_sum}") print(f"Average of the empty list: {empty_average}")

Output

 
OUTPUT  :
Original List: [10, 20, 30, 40, 50]
Sum of the list: 150
Average of the list: 30.0

Original List (Empty): []
Sum of the empty list: 0
Average of the empty list: 0