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.7. Map, filter and reduce 93List methods are all void; they modify the list and return None. If you accidentally write t =t.sort(),you willbe disappointed withthe result.10.7 Map,filterand reduceTo add up all thenumbers inalist,you can usealoop likethis:def add_all(t):total = 0for x in t:total += xreturn totaltotal is initialized to 0. Each time through the loop, x gets one element from the list. The +=operator provides ashortway toupdate avariable. This augmented assignment statement:total += xisequivalent to:total = total + xAs the loop executes, total accumulates the sum of the elements; a variable used this way issometimes called an accumulator.Adding up the elements of a list is such a common operation that <strong>Python</strong> provides it as a built-infunction,sum:>>> t = [1, 2, 3]>>> sum(t)6An operation like this that combines a sequence of elements into a single value is sometimes calledreduce.Sometimesyouwanttotraverseonelistwhilebuildinganother. Forexample,thefollowingfunctiontakes a listof stringsand returns anew listthat contains capitalized strings:def capitalize_all(t):res = []for s in t:res.append(s.capitalize())return resres is initialized with an empty list; each time through the loop, we append the next element. Soresisanother kind of accumulator.Anoperationlikecapitalize_allissometimescalledamapbecauseit“maps”afunction(inthiscase themethodcapitalize)onto each of theelements inasequence.Anothercommonoperationistoselectsomeoftheelementsfromalistandreturnasublist. Forexample,thefollowingfunctiontakesalistofstringsandreturnsalistthatcontainsonlytheuppercasestrings:

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

Saved successfully!

Ooh no, something went wrong!