reggaelizard reggaelizard - 1 year ago 86
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
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)
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)


Thanks in advance!

Answer Source

Using Python's builtin sum and len functions:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download