Apply a function to each list member?

Michael Hudson mwh21 at cam.ac.uk
Thu Oct 21 17:35:21 EDT 1999


Gaetan Corneau <Gaetan_Corneau at baan.com> writes:

> Hi,
> 
> Is there a way to do this (see "ListApply" below) with standard Python
> stuff?
> 
> def f(s):
>     from string import upper
>     from types import StringType
>     if type(s) == StringType:
>         return upper(s) 
>     else:
>         return s
> 
> 
> def ListApply(f, l):
>     for i in  range(0, len(l)):
>         l[i] = f(l[i])
> 
> 
> l = ["aaa", "bbb", "ccc", 1, 2, 3, "xxx", "yyy", "zzz"]
> print l
> 
> ListApply(f, l)
> print l

um... map?

l=map(f,l)

f *could* be defined as a lambda, but it'd be unspeakably hairy,
something like

f=lambda s,u=string.upper,t=types.StringType: \
             (type(s) is t and (u(s),) or (s,))[0]

but I'm going to presume you're not that silly.

Your ListApply might be a little more space efficient as it works in
place, but not much, because you allocate a list of length len(l)
anyway in the range().

HTH,
Michael

PS: Yes, all that hair *is* needed; consider f(0) or f("") before you
simplify...




More information about the Python-list mailing list