53
2.2 Lists
61
>>> C C = = [-10, , -5, , 0, , 5, 10, 15, 20, , 25, 30]
# create list
>>> C.append(35)
# add d new element 35 at t the e end
>>> C
# view w list t C
[-10, -5, 0, 5, 10, 15, 20, 25, 30, , 35]
Twolistscanbeadded:
>>> C C = = C C + + [40, , 45]
# extend C C at the end
>>> C
[-10, -5, 0, 5, 10, 15, 20, 25, 30, , 35, 40, 45]
Whataddingtwolistsmeansisuptothelistobjecttodefine,andnot
surprisingly,addition oftwolistsisdefinedasappendingthesecond
listtothefirst.Theresultof C + [40,45]isanewlistobject,which
wethenassigntoCsuchthatthisnamereferstothisnewlist.Infact,
everyobjectinPythonandeverythingyoucandowithitisdefinedby
programsmadebyhumans.Withthetechniquesofclassprogramming
(seeChapter7)youcancreateyourownobjectsanddefine(ifdesired)
whatitmeanstoaddsuchobjects.Allthisgivesenormouspowerinthe
handsofprogrammers.Asoneexample,youcandefineyourownlist
objectifyouarenotsatisfiedwiththefunctionalityofPython’sown
lists.
Newelementscanbeinsertedanywhereinthelist(andnotonlyat
theendaswedidwithC.append):
>>> C.insert(0, , -15)
# insert new element t -15 as index x 0
>>> C
[-15, -10, , -5, 0, 5, , 10, 15, , 20, 25, 30, 35, , 40, 45]
Withdel C[i]wecanremoveanelementwithindexifromthelistC.
Observethatthischangesthelist,soC[i]referstoanother(thenext)
elementaftertheremoval:
>>> del C[2]
# delete 3rd element
>>> C
[-15, -10, , 0, , 5, 10, 15, 20, , 25, 30, 35, 40, , 45]
>>> del C[2]
# delete what t is now 3rd element
>>> C
[-15, -10, , 5, , 10, , 15, 20, 25, 30, , 35, 40, 45]
>>> len(C)
# length of list
11
ThecommandC.index(10)returnstheindexcorrespondingtothefirst
elementwithvalue10(thisisthe4thelementinoursamplelist,with
index3):
>>> C.index(10)
# find d index x for r an n element t (10)
3
Tojusttestifanobjectwiththevalue10isanelementinthelist,one
canwritethebooleanexpression10 in C: