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 simple Python code to calculate the average (mean) of a list:
def calculate_average(numbers): if not numbers: # Check if list is empty return None return sum(numbers) / len(numbers) # Example usage numbers = [5, 10, 15, 20, 25] average = calculate_average(numbers) print(f"The average is: {average}") # Output: The average is: 15.0This code:
- Takes a list of numbers as input
- Checks if the list is empty to avoid division by zero
- Uses
sum()to add all numbers and divides by the length of the list - Returns None if the list is empty, otherwise returns the average
Would you like me to explain any part of this code in more detail?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.