mapping a method to a list?

Just van Rossum just at letterror.com
Wed Aug 8 19:05:59 CEST 2001


gyromagnetic at excite.com wrote:

> 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).
> 
> I think that map currently works by applying a function to each of the
> items in the list, but would it be useful for 'map' to be able to take
> a method instead of a function?

I think this is a great example of what list comprehensions were
designed for:

>>> val=['abc', 'def', 'ghi']
>>> [x.upper() for x in val]
['ABC', 'DEF', 'GHI']
>>> 

The non-list-comprehension version is indeed awkward:

>>> map(lambda x: x.upper(), val)
['ABC', 'DEF', 'GHI']
>>> 

Just



More information about the Python-list mailing list