12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

Variable-length, heterogeneous, and arbitrarily nestableUnlike strings, lists can grow and shrink in-place (their lengths can vary), and cancontain any sort of object, not just one-character strings (they’re heterogeneous).Because lists can contain other complex objects, they also support arbitrary nesting;you can create lists of lists of lists, and so on.Of the category mutable sequenceIn terms of our type category qualifiers, lists can be changed in-place (they’remutable), and can respond to all the sequence operations used with strings, suchas indexing, slicing, and concatenation. In fact, sequence operations work thesame on lists as they do on strings; the only difference is that sequence operationssuch as concatenation and slicing return new lists instead of new stringswhen applied to lists. Because lists are mutable, however, they also supportother operations that strings don’t (such as deletion and index assignment operations,which change the lists in-place).Arrays of object referencesTechnically, <strong>Python</strong> lists contain zero or more references to other objects. Listsmight remind you of arrays of pointers (addresses). Fetching an item from a<strong>Python</strong> list is about as fast as indexing a C array; in fact, lists really are C arraysinside the standard <strong>Python</strong> interpreter, not linked structures. As we learned inChapter 6, though, <strong>Python</strong> always follows a reference to an object whenever thereference is used, so your program deals only with objects. Whenever you assignan object to a data structure component or variable name, <strong>Python</strong> always storesa reference to that same object, not a copy of it (unless you request a copyexplicitly).Table 8-1 summarizes common and representative list object operations. As usual,for the full story, see the <strong>Python</strong> standard library manual, or run a help(list) ordir(list) call interactively for a full list of list methods—you can pass in a real list,or the word list, which is the name of the list data type.Table 8-1. Common list literals and operationsOperationInterpretationL1 = []An empty listL2 = [0, 1, 2, 3] Four items: indexes 0..3L3 = ['abc', ['def', 'ghi']]Nested sublistsL2[i]Index, index of index, slice, lengthL3[i][j]L2[i:j]len(L2)L1 + L2Concatenate, repeatL2 * 3Lists | 153

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

Saved successfully!

Ooh no, something went wrong!