Python Programming: An Introduction to Computer Science

(Nora) #1
11.2. APPLYINGLISTS 179

Whenthey wanttorefertospecificvaluesinthesequence,thesevaluesaredenotedbysubscripts. Inthis
example,thefirstiteminthesequenceis denotedwiththesubscript0,s 0.
Byusingnumbersassubscripts,mathematiciansareabletosuccinctlysummarizecomputationsover
itemsinthesequenceusingsubscriptvariables. Forexample,thesumofthesequenceiswrittenusing
standardsummationnotationas
n 1



i 0

si

A similarideacanbeappliedtocomputerprograms.We canusea singlevariabletorepresentanentire
sequence,andtheindividualitemsinthesequencecanbeaccessedthroughsubscripting.Well,almost;We
don’t have a wayoftypingsubscripts,butwecanuseindexinginstead.
Supposethatoursequenceis storedina variablecalleds. We couldwritea looptocalculatethesumof
theitemsinthesequencelike this:


sum = 0
for i in range(n):
sum = sum + s[i]


To make thiswork,smustbetherightkindofobject.InPython,wecanusea list;otherlanguageshave
arrays, whicharesimilar. A listorarrayis a sequenceofitemswheretheentiresequenceis referredtobya
singlename(inthiscase,s) andindividualitemscanbeselectedbyindexing(e.g.,s[i]).


11.2.2 Listsvs.Strings.


Youmaynoticethesimilaritybetweenlistsandstrings.InPythonstringsandlistsarebothsequencesthatcan
beindexed.Infact,allofthebuilt-instringoperationsthatwediscussedin Chapter4 aresequenceoperations
andcanalsobeappliedtolists.To jogyourmemory, here’s a summary.


Operator Meaning
seq + seq Concatenation
seq * int-expr Repetition
seq [ ] Indexing
len( seq ) Length
seq [ : ] Slicing
for var in seq : Iteration

Thelastlineshowsthataforloopcanbeusedto iteratethroughtheitemsin a sequence.Thesummation
exampleabove canbecodedmoresimplylike this:


sum = 0
for num in s:
sum = sum + s


Listsdifferfromstringsina coupleimportantways. First,theitemsina listcanbeany datatype,
includinginstancesofprogrammer-definedclasses.Strings,obviously, arealwayssequencesofcharacters.
Second,listsaremutable. Thatmeansthatthecontentsofa listcanbemodified.Stringscannotbechanged
“inplace.” Hereis anexampleinteractionthatillustratesthedifference:





myList = [34, 26, 15, 10]
myList[2]
15
myList[2] = 0
myList
[34, 26, 0, 10]
myString = "HelloWorld"
myString[2]




Free download pdf