12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

10.3. Traversing alist 9110.3 TraversingalistThe most common way to traverse the elements of a list is with a for loop. The syntax is the sameas forstrings:for cheese in cheeses:print cheeseThis works well if you only need to read the elements of the list. But if you want to write or updatethe elements, you need the indices. A common way to do that is to combine the functions rangeandlen:for i in range(len(numbers)):numbers[i] = numbers[i] * 2Thislooptraversesthelistandupdateseachelement. lenreturnsthenumberofelementsinthelist.range returns a list of indices from 0 to n−1, where n is the length of the list. Each time throughthe loop i gets the index of the next element. The assignment statement in the body uses i to readtheold value ofthe element and toassignthe new value.Aforloop over an empty listnever executes thebody:for x in []:print 'This never happens.'Althoughalistcancontainanotherlist,thenestedliststillcountsasasingleelement. Thelengthofthislistisfour:['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]10.4 ListoperationsThe+operator concatenates lists:>>> a = [1, 2, 3]>>> b = [4, 5, 6]>>> c = a + b>>> print c[1, 2, 3, 4, 5, 6]Similarly, the*operator repeats alistagiven number oftimes:>>> [0] * 4[0, 0, 0, 0]>>> [1, 2, 3] * 3[1, 2, 3, 1, 2, 3, 1, 2, 3]The first example repeats [0] four times. The second example repeats the list [1, 2, 3] threetimes.

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

Saved successfully!

Ooh no, something went wrong!