Python Programming: An Introduction to Computer Science

(Nora) #1
11.3. STATISTICSWITHLISTS 181

We have seenhow listscangrow byappendingnew items.Listscanalsoshrinkwhenitemsaredeleted.
Individualitemsorentireslicescanberemovedfroma listusingthedeloperator.





myList
[34, 26, 0, 10]
del myList[1]
myList
[34, 0, 10]
del myList[1:3]
myList
[34]





Asyoucansee,Pythonlistsprovidea veryflexiblemechanismforhandlingindefinitelylargesequences
ofdata.Usinglistsis easyif youkeepthesebasicprinciplesinmind:


 A listis a sequenceofitemsstoredasa singleobject.

 Itemsina listcanbeaccessedbyindexing,andsublistscanbeaccessedbyslicing.

 Listsaremutable;individualitemsorentireslicescanbereplacedthroughassignmentstatements.

 Listswillgrow andshrinkasneeded.

11.3 StatisticswithLists


Nowthatyouknowmoreaboutlists,wearereadytosolve ourlittlestatisticsproblem.Recallthatweare
tryingtodevelopa programthatcancomputethemean,medianandstandarddeviationofa sequenceof
numbersenteredbytheuser. Oneobviouswaytoapproachthisproblemis tostorethenumbersina list.We
canwritea seriesoffunctions—mean,stdDevandmedian—thattake a listofnumbersandcalculatethe
correspondingstatistics.
Let’s startbyusingliststorewriteouroriginalprogramthatonlycomputesthemean.First,weneeda
functionthatgetsthenumbersfromtheuser. Let’s callitgetNumbers. Thisfunctionwillimplementthe
basicsentinelloopfromouroriginalprogramtoinputa sequenceofnumbers.We willuseaninitiallyempty
listasanaccumulatortocollectthenumbers.Thelistwillthenbereturnedfromthefunction.
Here’s thecodeforgetNumbers:


def getNumbers():
nums = [] # startwith an empty list


# sentinel loopto get numbers
xStr = raw_input("Entera number (<Enter> to quit) >> ")
while xStr != "":
x = eval(xStr)
nums.append(x) # add this value to the list
xStr = raw_input("Entera number (<Enter> to quit) >> ")
return nums

Usingthisfunction,wecangeta listofnumbersfromtheuserwitha singlelineofcode.


data = getNumbers()


Next,let’s implementa functionthatcomputesthemeanofthenumbersina list.Thisfunctiontakesa
listofnumbersasa parameterandreturnsthemean.We willusea looptogothroughthelistandcompute
thesum.


def mean(nums):
sum = 0.0

Free download pdf