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.

94 Chapter 10. Listsdef only_upper(t):res = []for s in t:if s.isupper():res.append(s)return resisupperisastringmethod that returnsTrueifthestringcontains only upper case letters.An operation like only_upper is called a filter because it selects some of the elements and filtersout the others.Most common list operations can be expressed as a combination of map, filter and reduce. Becausethese operations are so common, <strong>Python</strong> provides language features to support them, including thebuilt-infunctionmapand an operator called a“listcomprehension.”Exercise 10.1 Write a function that takes a list of numbers and returns the cumulative sum; thatis, a new list where the ith element is the sum of the first i+1 elements from the original list. Forexample, the cumulative sum of[1, 2, 3]is[1, 3, 6].10.8 DeletingelementsThere are several ways to delete elements from a list. If you know the index of the element youwant, you can usepop:>>> t = ['a', 'b', 'c']>>> x = t.pop(1)>>> print t['a', 'c']>>> print xbpop modifies the list and returns the element that was removed. If you don’t provide an index, itdeletes and returns thelastelement.Ifyou don’t need the removed value, you can use thedeloperator:>>> t = ['a', 'b', 'c']>>> del t[1]>>> print t['a', 'c']Ifyou know theelement you want toremove (but not theindex), you can useremove:>>> t = ['a', 'b', 'c']>>> t.remove('b')>>> print t['a', 'c']The returnvalue fromremoveisNone.To remove more than one element, you can usedelwithasliceindex:

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

Saved successfully!

Ooh no, something went wrong!