reggaelizard reggaelizard - 6 days ago 7
Python Question

Average of all values in a list - is there a more 'Pythonic' way to do this?

So I'm following a beginner's guide to Python and I got this exercise:


Create a list containing 100 random integers between 0 and 1000 (use
iteration, append, and the random module). Write a function called
average
that will take the list as a parameter and return the average.


I solved it easily in a few minutes but the chapter also mentions several ways to traverse through lists and assign multiple values to lists and variables that I'm not sure if I fully understand yet, so I don't know if it's possible to do this in less lines. This is my answer:

import random

def createRandList():
newlist = []
for i in range(100):
newint = random.randrange(0,1001)
newlist.append(newint)
return newlist

def average(aList):
totalitems = 0
totalvalue = 0
for item in aList:
intitem = int(item)
totalitems = totalitems + 1
totalvalue = totalvalue + intitem
averagevalue = totalvalue/totalitems
return averagevalue

myList = createRandList()
listAverage = average(myList)

print(myList)
print(listAverage)


Thanks in advance!

Answer

Using Python's builtin sum and len functions:

print(sum(myList)/len(myList))