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.

In some types of programs, the list pop method used here is often used in conjunctionwith append to implement a quick last-in-first-out (LIFO) stack structure. Theend of the list serves as the top of the stack:>>> L = []>>> L.append(1) # Push onto stack>>> L.append(2)>>> L[1, 2]>>> L.pop( ) # Pop off stack2>>> L[1]Although not shown here, the pop method also accepts an optional offset of the itemto be deleted and returned (the default is the last item). Other list methods removean item by value (remove), insert an item at an offset (insert), search for an item’s offset(index), and more; see other documentation sources, or experiment with thesecalls interactively on your own to learn more.Other common list operationsBecause lists are mutable, you can use the del statement to delete an item or sectionin-place:>>> L['SPAM!', 'eat', 'more', 'please']>>> del L[0] # Delete one item>>> L['eat', 'more', 'please']>>> del L[1:] # Delete an entire section>>> L # Same as L[1:] = []['eat']Because slice assignment is a deletion plus an insertion, you can also delete a sectionof a list by assigning an empty list to a slice (L[i:j]=[]); <strong>Python</strong> deletes the slicenamed on the left, and then inserts nothing. Assigning an empty list to an index, onthe other hand, just stores a reference to the empty list in the specified slot, ratherthan deleting it:>>> L = ['Already', 'got', 'one']>>> L[1:] = []>>> L['Already']>>> L[0] = []>>> L[[]]Although all the operations just discussed are typical, there are additional list methodsand operations not illustrated here (including methods for inserting and searching).For a comprehensive and up-to-date list of type tools, you should always consultLists in Action | 159

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

Saved successfully!

Ooh no, something went wrong!