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.

92 Chapter 10. Lists10.5 ListslicesThe sliceoperator alsoworks on lists:>>> t = ['a', 'b', 'c', 'd', 'e', 'f']>>> t[1:3]['b', 'c']>>> t[:4]['a', 'b', 'c', 'd']>>> t[3:]['d', 'e', 'f']If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes totheend. Soif you omit both, the sliceisacopy of the whole list.>>> t[:]['a', 'b', 'c', 'd', 'e', 'f']Since lists are mutable, it is often useful to make a copy before performing operations that fold,spindle or mutilatelists.A sliceoperator on theleftsideof an assignment can update multipleelements:>>> t = ['a', 'b', 'c', 'd', 'e', 'f']>>> t[1:3] = ['x', 'y']>>> print t['a', 'x', 'y', 'd', 'e', 'f']10.6 Listmethods<strong>Python</strong> provides methods that operate on lists. For example, append adds a new element to the endof alist:>>> t = ['a', 'b', 'c']>>> t.append('d')>>> print t['a', 'b', 'c', 'd']extendtakes a listas an argument and appends all ofthe elements:>>> t1 = ['a', 'b', 'c']>>> t2 = ['d', 'e']>>> t1.extend(t2)>>> print t1['a', 'b', 'c', 'd', 'e']This example leavest2unmodified.sortarranges theelements of the listfrom low tohigh:>>> t = ['d', 'c', 'e', 'b', 'a']>>> t.sort()>>> print t['a', 'b', 'c', 'd', 'e']

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

Saved successfully!

Ooh no, something went wrong!