180 CHAPTER11. DATA COLLECTIONS
’l’
myString[2] = ’z’
Traceback (innermostlast):
File "", line1, in?
TypeError: object doesn’tsupport item assignment
Thefirstlinecreatesa listoffournumbers.Indexingposition2 returnsthevalue 15 (asusual,indexes
startat 0).Thenextcommandassignsthevalue0 totheiteminposition2.Aftertheassignment,evaluating
thelistshowsthatthenew valuehasreplacedtheold.Attemptinga similaroperationona stringproducesan
error. Stringsarenotmutable;listsare.
11.2.3 ListOperations.
Arraysinotherprogramminglanguagesaregenerallyfixedsize. Whenyoucreateanarray, youhave to
specifyhowmany itemsit willhold.If youdon’t knowhowmany itemsyouwillhave,thenyouhave to
allocatea largearray, justincase,andkeeptrackofhowmany “slots”youactuallyfill.Arraysarealso
usuallyhomogeneous. Thatmeansthey arerestrictedtoholdingobjectsofa singledatatype.Youcanhave
anarrayofintsoranarrayofstringsbutcannotmixstringsandintsina singlearray.
Incontrast,Pythonlistsaredynamic.They cangrow andshrinkondemand.They arealsoheterogeneous.
Youcanmixarbitrarydatatypesin a singlelist.Ina nutshell,Pythonlistsare mutablesequencesof arbitrary
objects.
Asyouknow, listscanbecreatedbylistingitemsinsidesquarebrackets.
odds = [1, 3, 5, 7, 9]
food = ["spam", "eggs","back bacon"]
silly = [1, "spam",4, "U"]
empty = []
Inthelastexample,emptyis a listcontainingnoitemsat all—anemptylist.
A listofidenticalitemscanbecreatedusingtherepetitionoperator. Thisexamplecreatesa listcontaining
50 zeroes:
zeroes = [0] * 50
Typically, listsarebuiltuponepieceat a timeusingtheappendmethod.Hereis a fragmentofcodethat
fillsa listwithpositive numberstypedbytheuser:
nums = []
x = input(’Enter a number:’)
while x >= 0:
nums.append(x)
x = input("Entera number: ")
Inessence,numsis beingusedasanaccumulator. Theaccumulatorstartsoutempty, andeachtimethrough
theloopa new valueis tackedon.
Theappendmethodis justoneexampleofa numberofusefullist-specificmethods.Thefollowingtable
brieflysummarizesofwhatyoucandotoa list:
Method Meaning
.append(x) Addelementx toendoflist.
.sort() Sortthelist.A comparisonfunctionmaybepassedasparameter.
.reverse() Reversesthelist.
.index(x) Returnsindex offirstoccurrenceofx.