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.

98 Chapter 10. ListsSince the listisshared by twoframes, Idrew itbetween them.It is important to distinguish between operations that modify lists and operations that create newlists. For example, theappendmethod modifies a list,but the+operator creates anew list:>>> t1 = [1, 2]>>> t2 = t1.append(3)>>> print t1[1, 2, 3]>>> print t2None>>> t3 = t1 + [3]>>> print t3[1, 2, 3]>>> t2 is t3FalseThisdifferenceisimportantwhenyouwritefunctionsthataresupposedtomodifylists. Forexample,thisfunction does not delete thehead of alist:def bad_delete_head(t):t = t[1:]# WRONG!Thesliceoperatorcreatesanewlistandtheassignmentmakestrefertoit,butnoneofthathasanyeffect on the listthat was passed as an argument.An alternative is to write a function that creates and returns a new list. For example, tail returnsall but thefirst element of alist:def tail(t):return t[1:]This function leaves the original listunmodified. Here’s how itisused:>>> letters = ['a', 'b', 'c']>>> rest = tail(letters)>>> print rest['b', 'c']Exercise 10.2 Write a function called chop that takes a list and modifies it, removing the first andlastelements, and returnsNone.Then write a function called middle that takes a list and returns a new list that contains all but thefirstand last elements.10.13 DebuggingCarelessuseoflists(andothermutableobjects)canleadtolonghoursofdebugging. Herearesomecommon pitfallsand ways toavoid them:1. Don’tforgetthatmostlistmethodsmodifytheargumentandreturnNone. Thisistheoppositeof the stringmethods, which returnanew stringand leave theoriginal alone.Ifyou areused towritingstringcode likethis:

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

Saved successfully!

Ooh no, something went wrong!