Apply function to each element of a list

function, list, list-comprehension, python, string

Solution

Using the built-in standard library `map`:

>>> mylis = ['this is test', 'another test']
>>> list(map(str.upper, mylis))
['THIS IS TEST', 'ANOTHER TEST']

In Python 2.x, `map` constructed the desired new list by applying a given function to every element in a list.

In Python 3.x, `map` constructs an iterator instead of a list, so the call to `list` is necessary. If you are using Python 3.x and require a list the list comprehension approach would be better suited.

Problem

Suppose I have a list like: ``` mylis = ['this is test', 'another test'] ``` How do I apply a function to each element in the list? For example, how do I apply `str.upper` to get: ``` ['THIS IS TEST', 'ANOTHER TEST'] ```

Original source

Related problems