2

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!

reggaelizard
  • 811
  • 2
  • 12
  • 31

2 Answers2

9

Using Python's builtin sum and len functions:

print(sum(myList)/len(myList))
John Y
  • 14,123
  • 2
  • 48
  • 72
jayelm
  • 7,236
  • 5
  • 43
  • 61
1

I agree with the suggestion above about using sum.

Though I don't love using a list comprehension just to run a fixed number of iterations, your createRandList function body could be simply:

return [random.randint(0,1000) for i in range(100)]

(Also, I find randint a little more readable because the "stop" value is the one you want, not the one you want + 1. )

In any case, you can dispense with the line where you call int() on your numbers -- the output of randrange is already int.

Paul Bissex
  • 1,611
  • 1
  • 17
  • 22
  • Although `randint` appeals to a more universal common sense, `randrange` is preferred due to its consistency with Python convention, e.g. `range(start, stop)` and the slice syntax (`[start, stop]`). In fact, randint has been deprecated multiple times in python history. See http://stackoverflow.com/a/2568917/2980246 – jayelm May 27 '14 at 04:22