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.14. Glossary 99word = word.strip()Itis tempting towritelistcode likethis:t = t.sort()# WRONG!BecausesortreturnsNone,thenext operation you perform withtislikelytofail.Beforeusinglistmethodsandoperators,youshouldreadthedocumentationcarefullyandthentestthemininteractivemode. Themethodsandoperatorsthatlistssharewithothersequences(like strings) are documented at docs.python.org/lib/typesseq.html. The methods andoperators that only apply to mutable sequences are documented at docs.python.org/lib/typesseq-mutable.html.2. Pick an idiom and stickwithit.Part of the problem with lists is that there are too many ways to do things. For example, toremove anelement fromalist,you can usepop,remove,del,oreven asliceassignment.To add an element, you can use the append method or the + operator. Assuming that t is alistandxisalistelement, these areright:t.append(x)t = t + [x]And these arewrong:t.append([x])t = t.append(x)t + [x]t = t + x# WRONG!# WRONG!# WRONG!# WRONG!Try out each of these examples in interactive mode to make sure you understand what theydo. Notice that only the last one causes a runtime error; the other three are legal, but they dothe wrong thing.3. Make copies toavoid aliasing.If you want to use a method like sort that modifies the argument, but you need to keep theoriginal listas well, you can make a copy.orig = t[:]t.sort()In this example you could also use the built-in function sorted, which returns a new, sortedlistandleavestheoriginalalone. Butinthatcaseyoushouldavoidusingsortedasavariablename!10.14 Glossarylist: A sequence of values.element: One of the values inalist(orother sequence), alsocalled items.index: Aninteger value that indicates an element inalist.

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

Saved successfully!

Ooh no, something went wrong!