[Tutor] Hmmm...

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 9 Mar 2001 18:38:43 -0800 (PST)


On Fri, 9 Mar 2001, Britt Green wrote:

> import string
> 
> theFruits = ['apple', 'banana', 'pineapple', 'pear', 'orange']
> 
> chosen = []
> 
> for stuff in theFruits:
>     if stuff.endswith('e'):
>         chosen.append(stuff)
> 
>     print chosen
> 
> When run, only the elements of theFruits that end with an 'e' will get
> added to the list of chosen. Is there a better way to do this?


Here's another wacky way to do that:

###
def endsWithE(word):
    return word.endswith('e')

theFruits = ['apple', 'banana', 'pineapple', 'pear', 'orange']
chosen = filter(endsWithE, theFruits)
print chosen
###

which tells Python: "Ok, let's filter out only theFruits that
endsWithE()."  This is called the "functional" approach, because all we're
doing is function calls and passing functions around.  It's a lot of fun.