12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

90 Chapter 10. Lists>>> print cheeses[0]CheddarUnlikestrings,listsaremutable. Whenthebracketoperatorappearsontheleftsideofanassignment,itidentifies the element of thelistthat willbe assigned.>>> numbers = [17, 123]>>> numbers[1] = 5>>> print numbers[17, 5]The one-eth element ofnumbers,which used tobe 123, is now 5.You can think of a list as a relationship between indices and elements. This relationship is calleda mapping; each index “maps to” one of the elements. Here is a state diagram showing cheeses,numbersandempty:cheeseslist012’Cheddar’’Edam’’Gouda’listnumbers 01171235emptylistLists are represented by boxes with the word “list” outside and the elements of the list inside.cheesesreferstoalistwiththreeelementsindexed0,1and2. numberscontainstwoelements;thediagramshowsthatthevalueofthesecondelementhasbeenreassignedfrom123to5. emptyreferstoalistwithnoelements.Listindices workthe sameway as stringindices:• Any integer expression can beused as an index.• Ifyou trytoread or writean element that does not exist,you get anIndexError.• Ifan index has anegative value, itcounts backward from theend of the list.Theinoperator alsoworks on lists.>>> cheeses = ['Cheddar', 'Edam', 'Gouda']>>> 'Edam' in cheesesTrue>>> 'Brie' in cheesesFalse

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!