give me some python code to calculate the average of a list
- User
give me some python code to calculate the average of a list
Assistant
Here's a Python function to calculate the average of a list, including error handling for empty lists:
pythondef calculate_average(numbers): if not numbers: return None # Return None for empty lists return sum(numbers) / len(numbers) # Example usage: my_list = [10, 20, 30, 40, 50] print(calculate_average(my_list)) # Output: 30.0Explanation:
- Error Handling: Checks if the list is empty using
if not numbersto avoid division by zero. - Calculation: Uses
sum()to get the total andlen()for the count of elements. - Return Value: Returns if the list is empty (you could also raise an exception).
- Error Handling: Checks if the list is empty using
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.