Download on lists, slicing lists, list methods

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Vincent's theorem wikipedia , lookup

Transcript
CompSci101-PrinciplesofProgramming
2
Learningoutcomes
! Attheendofthislecture,studentsshouldbeableto:
!  slicelists
!  usevariouslistmethods
!  understandthedifferencebetween'=='and'is'
COMPSCI11
PrinciplesofProgramming
Lecture17-Slicinglists,somelistmethods
ListsRecap
CompSci101-PrinciplesofProgramming
3
!  Lists
!  anemptylist
list1 = []! or
list1 = list()
!  alistofints
list2 = [2, 3, 4] !
!  alistofstrings
list3 = ["red", "blue"] !
!  anintegerlistusingtherangefuncKon
!  alistcanincludemixedtypes
!
my_list = [10, 20, 30, 40, 50]!
print(len(my_list))!
list4 = list(range(3, 6)) !
[4, True, "Test", 34.8]!
[1, 2, "jim"]!
4
Thelen()funcKon
! Elementsaretheindividualitemsinalist.
! Thelen()funcKoncanbeusedtogetthelengthofalist.
!  Elementsareseparatedbycommasandenclosedinsquarebrackets,
!  Orderedsequenceofitemsofanytypes
!  CreateLists
CompSci101-PrinciplesofProgramming
5
! Specificelementsofalistcanbeaccessedusinganintegerindex
whichindicatestheposiKonoftheelementinthelist(starKngfrom
posiKon0).
CompSci101-PrinciplesofProgramming
5
CompSci101-PrinciplesofProgramming
Accessinglistelements
! Specificelementsinalistcanbemanipulatedusingsquarebracket
notaKonwiththeindexnumberoftheelementtobeaccessed.
Accessinglistelements
! Theelementsofalistcanbeaccessedfromtheendofthelistby
usinganegaKveindexvalue.
my_list = [10, 20, 30, 40, 50]!
print(my_list[-4])!
my_list[-3] = my_list[-1] + my_list[–2]!
print(my_list[-3], my_list[1], my_list[-5])!
my_list = [10, 20, 30, 40, 50]!
print(my_list[2])!
my_list[3] = my_list[1] + my_list[len(my_list) – 1]!
print(my_list[0], my_list[3])!
30
1070
my_list
0 10
20
9090,10
my_list
20
0
10
-5
2
30
1
20
-4
3
40
2
30
-3
4
50
3
40
-2
4
50
-1
1
6
Thiswayofwri=ng'len(my_list)-…'toaccesselementsfromtheendofthelistscanbeavoided
CompSci101-PrinciplesofProgramming
7
CompSci101-PrinciplesofProgramming
IndexoutofRange-IndexError
! Warning!Ifyoutrytoaccessanelementthatdoesnotexist,Python
willthrowanerror!
my_list = [10, 20, 30, 40, 50]!
print(my_list[5])!
#NO!Elementatindex5doesnotexist
#NO!Elementatindex-6doesnotexist
print(my_list[-6])!
The'in'Operator(membership)
! Theinoperatorreturnsaboolean.ItreturnsTrueifthevalue(on
theleYhandsideoftheinoperator)isanelementofthelist.
OtherwisetheinoperatorreturnsFalse.
!
my_list = [10, 20, 30, 40, 50]!
result1 = 100 in my_list!
!
IndexError:listindexoutofrange
my_list
0
10
-5
1
20
-4
2
30
-3
3
40
-2
4
50
-1
8
print(result1)!
print(30 in my_list)!
print(40 not in my_list)!
!
False
True
False
CompSci101-PrinciplesofProgramming
9
CompSci101-PrinciplesofProgramming
VisiKngeachelementinalist(iteraKon)
list2 = [100, 200]!
!
Youcanonly
concatenatetwolist
objects(notalistobject
andastringobject,nota
listobjectandaninteger
object).
60
Thevaluesintheelementsofalistcanbechangedusingafor…in
range(…)loop,e.g., my_list = [10, 20, 30, 40, 50]!
for index in range(len(my_list)):!
!
!
!if my_list[index] % 4 == 0:!
! !my_list[index] = my_list[index] + 1!
print(my_list)!
list3 = list1 + list2!
!
print("1.", list3)!
print("2.", 100 in list1)!
print("3.", 40 not in list2)!
!
list3 = list3 + [-4]!
print("4.", list3)!
1.[10,20,30,40,50,100,200]
2.False
3.True
4.[10,20,30,40,50,100,200,-4]
!
[10, 21, 30, 41, 50]!
CompSci101-PrinciplesofProgramming
The+Operator(concatenaKon)
! Applyingthe+operatortotwolistsproducesanewlistcontaining
alltheelementsofthefirstlistfollowedbyalltheelementsofthe
secondlist.
list1 = [10, 20, 30, 40, 50]!
! Wecaniteratethroughalltheelementsofalist,inorder,usinga
for…inloop,e.g., my_list = [10, 20, 30, 40, 50]!
total = 0!
for element in my_list:!
!if element % 4 == 0:!
! !total = total + element!
print(total)!
11
CompSci101-PrinciplesofProgramming
Exercise
! Completetheget_name_list()funcKonwhichreturnsalistofallthe
namesintheparameter,name_list,whichcontainthelecergiven
bytheparameter,to_look_for.
def get_name_list(name_list, to_look_for):!
!#complete!
!
!
!
!
!
!
!
def main():!
!names = ["Jasper", "Jade",
…, "Mikey", "Gianni"]!
!names_d = get_name_list(names, "d")!
!names_k = get_name_list(names, "k")!
!print("names with d", names_d)!
!print("names with k", names_k)!
!
nameswithd['Jade','Nikodem']
main()!
nameswithk['Nikodem','Mikey']
10
12
The*Operator(repeat)
! The*operatorproducesanewlistwhich"repeats"theoriginallist's
contents.
Youcanonlyrepeatalist
incombinaKonwithan
integer,i.e.,
the_list*an_integer.
list1 = [10, 20]!
list2 = list1 * 2!
list3 = list2 * 3!
!
print("1.", list1)!
print("2.", list2)!
print("3.", list3)!
1.[10,20]
2.[10,20,10,20]
3.[10,20,10,20,10,20,10,20,10,20,10,20]
CompSci101-PrinciplesofProgramming
13
CompSci101-PrinciplesofProgramming
Gegngslicesoflists
! ThesliceoperaKonbehavesthesamewayasitdoeswiththe
elementsofastring.Withinsquarebrackets,youmayhaveoneor
twocolons(:).Thenumberbeforethefirstcolonisthestartindex,
thenumberaYerthefirstcolonistheendindex,andthenumber
aYerthesecondcolonisthestep.
! Thestepindicatesthegapbetweenelementsintheslicetaken.The
defaultstepis1.
! Slicingreturnsanewlistobject.
list1 = [10, 20, 30, 40, 50]!
list2 = list1[0:3:1]!
print("1.", list2)!
!
list3 = list1[3:5:1]!
print("2.", list3)!
Does
the
same
job
as:
Gegngslicesoflists
! Thenumberbeforethefirstcolonisthestartindex,thenumber
aYerthefirstcolonistheendindex,andthenumberaYerthe
secondcolonisthestep.
list1 = [10, 20, 30, 40, 50, 60]!
list2 = list1[0:5:3] !
print("1.", list2)!
!
list3 = list1[2:5:2]!
print("2.", list3)!
list1 = [10, 20, 30, 40, 50]!
list2 = list1[0:3]
!
print("1.", list2)!
!
list3 = list1[3:5]
print("2.", list3)!
14
1.[10,40]
2.[30,50]
!
1.[10,20,30]
2.[40,50]
CompSci101-PrinciplesofProgramming
15
CompSci101-PrinciplesofProgramming
Gegngslicesoflists
! ThenumberaYerthesecondcolonisthestep.Thestepcanbea
negaKvenumber.Thedefaultstepis1(seepreviousslide).
list1 = [10, 20, 30, 40, 50, 55]!
list2 = list1[1:6:-3]!
print("1.", list2)!
!
list1
0
-6
1
-5
list3 = list1[-1:-4:-2]!
print("2.", list3)!
!
2
list4 = list1[-1:-6:-2]!
print("3.", list4)!
4
1.[]
2.[55,40]
3.[55,40,20]
3
5
Gegngslicesoflists
! Threenumbersinsquarebracketsseparatedbycolonsdefinethe
start,endandstepoftheslice,e.g.,list1[1:6:3].
! Thedefaultforthefirstnumberisthebeginningofthelist,e.g.,
list1 = [10, 20, 30, 40, 50, 55]!
list2 = list1[:4:1]
!#same as list2 = list1[0:4:1]!
print(list2)!
-4
-3
-2
-1
16
[10,20,30,40]
! Thedefaultforthesecondnumberistheendofthelist,e.g.,
list1 = [10, 20, 30, 40, 50, 55]!
list2 = list1[2::2]
#same as list2 = list1[2:len(list1):2]!
print(list2)!
[30,50]
Thedefaultforthestepvalueis1.
17
CompSci101-PrinciplesofProgramming
CompSci101-PrinciplesofProgramming
Exercise
! Completethesplit_and_merge()funcKonwhichsplitstheparameter
listintotwolists(downthemiddle)andmergesthetwolists.The
mergedlistisreturned.Assumethelisthasanevennumberof
elements.
def split_and_merge(number_list):!
number_list!
!
0 25
!
!
1 5
!
2 9
!
!
3 10
!
4 15
!
5 8
def main():!
!numbers1 = [25, 5, 9, 10, 15, 8]!
!numbers2 = split_and_merge(numbers1)!
!print(numbers1)!
!print(numbers2)!
!
[25,5,9,10,15,8]
main()!
[25,10,5,15,9,8]
25
10
5
15
9
8
0
25
1
10
2
5
3
15
4
9
5
8
1.sweetsweet
2.True
3.sweetsweetdumpling
4.False
word2
11011001
11011001
word2
10010111
==
is
word2)!
print("2.", word1
word2)!
!
word2 = word2.upper()!
word2 = word2.lower()!
!
print("3.", word1
print("4.", word1
==
is
word1
11011001
word2
11011001
word2)!
word2)!
11011001
"sweet"
1.True
2.True
3.True
4.False
11011001
word1
11011001
word2
10010111
19
11011001
"sweet"
11011001
word1
! Theisoperatorisusedtotestiftwovariablesreference(pointto)
thesameobject.
print("1.", word1
! Stringsare"immutable",i.e.,thecharactersinastringobject
cannotbechanged.Wheneverastringischangedinsomeway,a
newstringobject(withanewmemoryaddress)iscreated.
11011001
! The==operatorisusedtotestiftwoobjectscontainthesame
informaKon.
word1 = "sweet"!
word2 = word1!
Stringsareimmutable
word1
Theisoperator
"sweet"
10010111
"sweet"
Returned list!
CompSci101-PrinciplesofProgramming
word1 = "sweet"!
word2 = word1!
print("1.", word1, word2)!
print("2.", word1 is word2)!
!
word2 = word2 + " dumpling"!
print("3.", word1, word2)!
print("4.", word1 is word2)!
18
"sweet"
10010111
"sweetdumpling"
CompSci101-PrinciplesofProgramming
20
ListsareMutable
! Listsare"mutable",i.e.,theelementsin
alistobjectcanbeupdatedandadjusted.
list1 = [10, 20, 30,
list2 = [1, 5] #A!
print("1.", list1)!
print("2.", list2)!
print("3.", list1 is
!
list2 = list1 #B!
print("4.", list1 is
!
list1[3] = 99!
list2[1] = 3
#C!
!
print("5.", list1)!
print("6.", list2)!
print("7.", list1 is
40, 50]!
list2)!
list2)!
1.[10,20,30,40,50]
2.[1,5]
3.False
list2)! 4.True
5.[10,3,30,99,50]
6.[10,3,30,99,50]
7.True
CompSci101-PrinciplesofProgramming
21
CompSci101-PrinciplesofProgramming
SomeinbuiltfuncKonswhichworkwithlists
DotnotaKon
! Weusedotnota=ontocallamethodonaspecificobject.Indot
notaKon,adotisplacedbetweentheobjectandthemethodwhich
istobeappliedtotheobject.
! Eachtypeofobjecthasmanymethodswhichcanbecalledwiththat
typeofobject.Forexampleastringobjecthasthemethodsfind(),
upper(),lower(),strip(),isdigit(),isalpha(),andmanymore:
! Belowarefourin-builtfuncKonswhichcanbeusedwithlists:
! len(a_list)returnsthenumberofelements.
! min(a_list)returnstheminimumelementinthelist.
! max(a_list)returnsthemaximumelementinthelist.
! sum(a_list)returnsthesumoftheelementsinthelist(onlyfor
numbers).
list1 = [10, 20, 30, 40, 50, 55]!
minimum = min(list1)!
total = sum(list1)!
print("length:", len(list1), "min:", minimum, "max:", !
max(list1), "sum:", total)!
words = "Over the rainbow"!
position = words.find("r")!
words = words.lower()!
result = words.isalpha()!
!
print("position:", position,"words:", words, "result:", result)!
posi=on:3words:overtherainbowresult:False
length:6min:10max:55sum:205
CompSci101-PrinciplesofProgramming
23
CompSci101-PrinciplesofProgramming
Somelistmethods
! Therearemanymethodswhichcanbeusedwithlistobjects.Below
andonthenextslidesarefivemethodswhichcanbeusedwithlists:
! index(x)returnstheindexofthefirstelementfromtheleYinthe
listwithavalueequaltox.Pythonthrowsanerrorifthereisno
suchvalueinthelist.Becauseofthis,index(x)isusuallypreceded
byacheckforthatelementusingtheinoperator.
! pop(index)removesandreturnstheitemattheposiKongivenby
theindexnumber.The'popped'elementisreturnedbythe
method.Anerrorresultsifthereisnosuchindexinthelist.
pop()withnoindexremovesandreturnsthelastitem.
!
!
40isinposi=on3inthelist
24
Somelistmethods
list1 = [10, 20, 30, 40, 50, 55]!
list1 = [10, 20, 30, 40, 50, 55]!
if 40 in list1:
!
!
!#check first!
!position = list1.index(40)!
!print("40 is in position", position, "in the list")!
else:!
!print("40 is not in the list")!
22
if len(list1) > 2: !
!
!!
!popped = list1.pop(2)!
!
print("Popped item", popped, " from the list", list1)!
print(list1.pop())!
Poppeditem30fromthelist[10,20,40,50,55]
55
CompSci101-PrinciplesofProgramming
25
Anotherlistmethod
! insert(i,x)insertsanelementatagivenposiKon.Thefirst
argumentistheindexatwhichtoinserttheelement,e.g.,my
list.insert(1,62)inserts62intoposiKon1ofthelist,movingthe
restoftheelementsalongone(theelementatindex1movesto
index2,theelementatindex2movestoindex3,andsoon).
Anotherlistmethod
list1 = [10, 20, 30, 40, 50, 55]!
list1.append(77)!
print("1.", list1)!
!
list1.append(99)!
print("2.", list1)!
!
list1.append(44)!
print("3.", list1)!
1.[10,20,30,40,50,55,77]
2.[10,20,30,40,50,55,77,99]
3.[10,20,30,40,50,55,77,99,44]
27
Moreusefullistmethods
! sort()sortstheelementsofthelist,inplace.IfsorKngalistoflists,
onlythefirstelementineachlistisconsideredinthecomparison
operaKons.Onlytheorderofthelistelementsismodified(unless
alreadysorted).
list1 = [60, 20, 80, 10, 30, 55]!
print(list1)!
list1.sort()!
[60,20,80,10,30,55]
print(list1)!
[10,20,30,55,60,80]
! reverse()reversestheelementsofthelist,inplace.Onlytheorder
ofthelistelementsismodified.
list1 = [10, 20, 30, 40, 50, 55]!
print(list1)!
list1.reverse()!
[10,20,30,40,50,55]
print(list1)!
[55,50,40,30,20,10]
26
! append(x)addstheelementtotheendofthelist.
list1 = [10, 20, 30, 40, 50, 55]!
list1.insert(3, 77)!
print(list1)!
!
list1.insert(6, 99)!
print(list1)!
!
list1.insert(0, 44)!
print(list1)!
[10,20,30,77,40,50,55]
[10,20,30,77,40,50,99,55]
[44,10,20,30,77,40,50,99,55]
CompSci101-PrinciplesofProgramming
CompSci101-PrinciplesofProgramming
CompSci101-PrinciplesofProgramming
28
Exercise
! Completetheget_index_list()funcKonwhichreturnsasortedlistof
alltheindicesofthenumbers_to_look_forwhichexistinthelist
parameter,number_list.
def get_index_list(number_list, numbers_to_look_for):!
!
!
!
!
!
!
!
!
def main():!
!numbers = [1206, 1216, 475, 1038, 1481, 135]!
!search_numbers = [1038, 1367, 1206, 740, 1281, 1216]!
!index_list = get_index_list(numbers, search_numbers)!
!print("indices of the numbers found", index_list)!
!
!
indicesofthenumbersfound[0,1,3]
main()!
CompSci101-PrinciplesofProgramming
29
CompSci101-PrinciplesofProgramming
Exercise
! Completetheremove_mulKples()funcKonwhichremovesallthe
elementsintheparameterlist,number_list,whicharemulKplesof
theparameter,mulKples_of.
CompSci101-PrinciplesofProgramming
!  Weuseafor…in…toiteratethroughthecontentsofalist
!  len()returnsthenumberofelementsinalist
!  min()returnstheminimumoftheelementsinalist
!  max()returnsthemaximumoftheelementsinalist
!  sum()returnsthesumoftheelementsinalist
!  Eachelementofthelistcanbeaccessedusingtheindexoperator.Theindexcanbe
negaKve(starKngfromtheendofthelist)
!  Slicesoflistscanbeobtainedbyusing[slice_start:slice_end:step]
!  index(element)returnstheindexoftheelementinalist
!  insert(posiKon,element)insertsanelementintoalistintotherequiredposiKon
!  append(element)addstheelementtotheendofthelist
!  reverse()reversestheelementsofalistinplace
!  sort()sortstheelementsofalistinplace
!  Listsaremutable
31
ExamplesofPythonfeaturesusedinthislecture
list1=[4,6,2,5,8]
result=8inlist1
forelementinlist1:
…
min_value=len(list1)
min_value=min(list1)
max_value=max(list1)#ifthelistelementsarenumbers
total=sum(list1)#ifthelistelementsarenumbers
element_from_end=list1[-2]
list2=list1[1:5:2]
posiKon=list1.index(3)
element=list1.pop(1)
list1.insert(4,66)
list1.append(54)
list1.reverse()
list1.sort()
Summary
! Aliststoresdataasasequence
def remove_multiples(number_list, multiples_of):!
!
!
!
!
!
!
!
!
!
def main():!
!numbers = [25, 5, 9, 10, 15, 8]!
!print(numbers)!
!remove_multiples(numbers, 5) #remove multiples of 5!
!print("Numbers left", numbers)!
!
[25,5,9,10,15,8]
main()!
Numbersle`[9,8]
30