15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

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.

How to Update Lists<br />

You can update single or multiple elements of lists by giving the slice on the left-hand side of the<br />

assignment operator, and you can add to elements in a list with the append() method:<br />

>>> aList<br />

[123, 'abc', 4.56, ['inner', 'list'], (7-9j)]<br />

>>> aList[2]<br />

4.56<br />

>>> aList[2] = 'float replacer'<br />

>>> aList<br />

[123, 'abc', 'float replacer', ['inner', 'list'], (7-9j)]<br />

>>><br />

>>> anotherList.append("hi, i'm new here")<br />

>>> print anotherList<br />

[None, 'something to see here', "hi, i'm new here"]<br />

>>> aListThatStartedEmpty.append('not empty anymore')<br />

>>> print aListThatStartedEmpty<br />

['not empty anymore']<br />

How to Remove List Elements and Lists<br />

To remove a list element, you can use either the del statement if you know exactly which element(s)<br />

you are deleting or the remove() method if you do not know.<br />

>>> aList<br />

[123, 'abc', 'float replacer', ['inner', 'list'], (7-9j)]<br />

>>> del aList[1]<br />

>>> aList<br />

[123, 'float replacer', ['inner', 'list'], (7-9j)]<br />

>>> aList.remove(123)<br />

>>> aList<br />

['float replacer', ['inner', 'list'], (7-9j)]<br />

You can also use the pop() method to remove and return a specific object from a list.<br />

Normally, removing an entire list is not something application programmers do. Rather, they tend to let<br />

it go out of scope (i.e., program termination, function call completion, etc.) and be deallocated, but if<br />

they do want to explicitly remove an entire list, they use the del statement:<br />

del aList

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

Saved successfully!

Ooh no, something went wrong!