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.

122 Chapter 12. TuplesInmanycontexts,thedifferentkindsofsequences(strings,listsandtuples)canbeusedinterchangeably.So how and why doyou choose one over theothers?To start with the obvious, strings are more limited than other sequences because the elements havetobecharacters. Theyarealsoimmutable. Ifyouneedtheabilitytochangethecharactersinastring(asopposed tocreating anew string),you might want tousealistof characters instead.Lists are more common than tuples, mostly because they are mutable. But there are a few caseswhere you might prefer tuples:1. In some contexts, like a return statement, it is syntactically simpler to create a tuple than alist. Inother contexts, you might prefer a list.2. If you want to use a sequence as a dictionary key, you have to use an immutable type like atuple or string.3. If you are passing a sequence as an argument to a function, using tuples reduces the potentialfor unexpected behavior due toaliasing.Because tuples are immutable, they don’t provide methods like sort and reverse, which modifyexisting lists. But <strong>Python</strong> provides the built-in functions sorted and reversed, which take anysequence as aparameter and returnanew listwiththe sameelements inadifferent order.12.9 DebuggingLists, dictionaries and tuples are known generically as data structures; in this chapter we are startingto see compound data structures, like lists of tuples, and dictionaries that contain tuples as keysand lists as values. Compound data structures are useful, but they are prone to what I call shapeerrors; that is, errors caused when a data structure has the wrong type, size or composition. Forexample, ifyouareexpectingalistwithoneintegerandIgiveyouaplainoldinteger(notinalist),itwon’t work.To help debug these kinds of errors, I have written a module called structshape that provides afunction, also called structshape, that takes any kind of data structure as an argument and returnsa string that summarizes its shape. You can download it from thinkpython.com/code/structshape.pyHere’s theresult forasimplelist:>>> from structshape import structshape>>> t = [1,2,3]>>> print structshape(t)list of 3 intAfancierprogrammightwrite“listof3ints,”butitwaseasiernottodealwithplurals. Here’salistof lists:>>> t2 = [[1,2], [3,4], [5,6]]>>> print structshape(t2)list of 3 list of 2 intIftheelements of the listarenot thesame type,structshapegroups them, inorder, by type:

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

Saved successfully!

Ooh no, something went wrong!