mapping a method to a list?

Skip Montanaro skip at pobox.com
Wed Aug 8 13:31:57 EDT 2001


    Brad> For a simple example, suppose that I want to convert the items in
    Brad> a list to uppercase. Currently, I might do something like

    >>> import string
    >>> val=['abc', 'def', 'ghi']
    >>> map(string.upper, val)
    ['ABC', 'DEF', 'GHI']

    Brad> Is there a way to map the .upper method to these items? Something
    Brad> like, for example,
    >>> map(?.upper, val). 

How about using a list comprehension?

    [x.upper() for x in val]

    Brad> I think that map currently works by applying a function to each of
    Brad> the items in the list, but would it be useful for 'map' to be able
    Brad> to take a method instead of a function?

List comprehensions are relatively new to Python (as of 2.0).  You can see
more examples in the tutorial:

    http://www.python.org/doc/current/tut/node7.html

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list