gpt-4-0125-preview· OpenAI
WildChat-4.8M (AI2)
write a function to compute average of a python list
- User
write a function to compute average of a python list
- Assistant
To compute the average of a list in Python, you can write a simple function that sums up all the elements in the list and then divides that sum by the number of elements in the list. Here's an example of how you can do this:
def average(lst): if len(lst) == 0: return 0 # Return 0 or an appropriate value for an empty list return sum(lst) / len(lst) # Example usage: my_list = [10, 20, 30, 40, 50] print(average(my_list)) # Output: 30.0In this function,
sum(lst)calculates the total sum of all elements in the listlst, andlen(lst)gives you the total number of elements in the list. Dividing the sum by the count gives you the average. Note that if the list is empty, you'll want to handle that case accordingly (in this example, it returns 0, but you might want to returnNoneor raise an exception depending on your needs).