Lists in Python - Kalamazoo College

[Pages:3]ListsinPython

Ingeneral,wecandefinealistasanobjectthatcontainsmultipledataitems

(elements).Thecontentsofalistcanbechangedduringprogramexecution.The

sizeofalistcanalsochangeduringexecution,aselementsareaddedorremoved

fromit.WehaveseenseveralexamplesoflistsinPython.Soundsarelistsofsample

objects.Picturesarelistscontaininglistsofpixelobjects.Whenweuseaforloop,

weiterateoveralistofitems.Wehavetypicallyusedlistsofpixels,listsofsamples,

orlistsofintegerswithinacertainrangeinourforloops.

Wewillnowlookathowwecancreatelists andhowwecanworkdirectlywithlists.Most ofourpreviousexperiencewithlistshasbeen usingfunctionstoreturnliststous. Examplesoflists: numbers = [1, 2, 3, 4, 5] names = ["Pam", "Sue", "Dan",

Aside: Lists vs. Arrays Manyprogramminglanguagesallow youtocreatearrays,whichare objectssimilartolists.Sincelists servethesamepurposeasarrays andhavemanymorebuilt-in capabilities,traditionalarrays cannotbecreatedinPython.

"Sandi"]

info = ["Jordan", 123876, "Jr"]

Noticethatsquarebracketsareusedtoenclosetheelementsinalist,andthe

elementsthemselvesareseparatedbycommas.

Listscanbecreatedusingtherepetitionoperator,*.Weareaccustomedtousingthe

*symboltorepresentmultiplication,butwhentheoperandontheleftsideofthe*

isalist,itbecomestherepetitionoperator.Therepetitionoperatormakesmultiple

copiesofalistandjoinsthemalltogether.Thegeneralformatis:

list*n,

wherelistisalist,andnisthenumberofcopiestomake.

Examples(youcouldtrytheseonthecommandlineinJES)

>>> numbers = [0] * 5

>>> print numbers

[0, 0, 0, 0, 0]

Inthisexample,[0]isalistwithoneelement,0.Therepetitionoperatormakes5

copiesofthislistandjoinsthemalltogetherintoasinglelist.

>>> moreNumbers = [1, 2, 3] * 3

>>> print moreNumbers

[1, 2, 3, 1, 2, 3, 1, 2, 3]

Inthisexample,[1,2,3]isalistwiththreeelements,1,2,and3.Therepetition

operatormakes3copiesofthislistandjoinsthemtogetherintoasinglelist.

WhenweusedsoundfunctionssuchasgetSampleValueAtand

setSampleValueAtwewereusingindicestogetandsetthevalueofparticular

samples(elements)fromoursound.(Remember,asoundisalistofsample

objects.)Eachelementofalisthasanindexthatspecifiesitspositioninthelist.The

indexofthefirstelementofalistis0,theindexofthesecondelementis1,andso

on.Theindexofthelastelementofthelistis1lessthanthenumberofelementsin

thelist.If,forexample,wehave5elementsinourlist,theindiceswouldbe0,1,2,3,

4.

Wecandirectlymodifyourlistbyusingtheindexoftheelementwewanttochange.

Forexample,supposewehavethelistnames= ["Pam", "Sue", "Dan",

"Sandi"]andwewanttochangethethirdelementofthelisttobe"John"instead

of"Dan".Wecandothiswiththefollowingstatement:

names[2]="John"

Thelistthenbecomes["Pam", "Sue", "John", "Sandi"].Thegeneral

formatforaccessingindividualelementsofalistis:

list[index],

wherelististhenameofthelistandindexisthepositionoftheelementinthelistto

beaccessed.

Example:Afunctionthatwillcreatealisttostorethesumsofthevaluesintwolists

ofequallength.

def sumLists(list1, list2):

newList = [0] * len(list1)

(1)

# get the values from the two lists

# store the sum in the new list

for index in range(len(list1)):

(2)

newList[index] = list1[index] + list2[index]

return newList Noticethatinlines(1)and(2)weusethefunctionlen,abuilt-inPythonfunction thatreturnsthenumberofelementsinthelist. Exercise:Writeafunction,reverseList,thattakesalistasinputandreturnsa newlistthatisthereverseoftheoriginallist. Exercise:Writeafunction,concatenateLists,thattakestwolistsasinputand returnsanewlistthatcontainsalloftheelementsofthefirstlistfollowedbyallof theelementsofthesecondlist.Forexample,

>>> list1 = [1, 2, 3, 4, 5] >>> list2 = [6, 7, 8, 9] >>> list3 = concatenateLists(list1, list2) >>> print list3 [1, 2, 3, 4, 5, 6, 7, 8, 9]

Aside: Concatenating Lists InPythonwecanactuallyusethe+operatortoconcatenatelists.Inthe examplegivenintheexerciseabove,wecouldusethestatement list3=list1+list2 togetlist3asthelist[1,2,3,4,5,6,7,8,9].Forgoodpracticeworking withlists,thefunctionyouwriteinthepreviousexerciseshouldNOT usethe+operatortoconcatenatethelists.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download