mapping a method to a list?

Tim Hochberg tim.hochberg at ieee.org
Wed Aug 8 12:54:35 EDT 2001


<gyromagnetic at excite.com> wrote in message
news:3b716759.126576344 at 127.0.0.1...
> Hi,
> I am a relative newbie to Python, so this question may be quite naive.
> Is there a way to 'map' methods to a list of items?
>
> For a simple example, suppose that I want to convert the items in a
> list to uppercase. Currently, I might do something like
> >>> import string
> >>> val=['abc', 'def', 'ghi']
> >>> map(string.upper, val)
> ['ABC', 'DEF', 'GHI']
>
> Is there a way to map the .upper method to these items? Something
> like, for example,
> >>>>map(?.upper, val).

Did you try the obvious thing? It should work. For example:

   class Monty:
       def spammify(self, text):
           return "spam & %s" % text

   l = ["eggs", "baked beans", "sausage"]
   m = Monty()

   print map(m.spammify, l)
   # or equivalently
   print [m.spammify(item) for item in l]

produces:

   ['spam & eggs', 'spam & baked beans', 'spam & sausage']
   ['spam & eggs', 'spam & baked beans', 'spam & sausage']

Or did you mean something completely different?

-tim







More information about the Python-list mailing list