Apply function to each element of a list


Python Problem Overview

How do I apply a function to the list of variable inputs? For e.g. the filter function returns true values but not the actual output of the function.

from string import upper
mylis=['this is test', 'another test']

filter(upper, mylis)
['this is test', 'another test']

The expected output is :


I know upper is built-in. This is just an example.

Python Solutions

Solution 1 - Python

I think you mean to use map instead of filter:

>>> from string import upper
>>> mylis=['this is test', 'another test']
>>> map(upper, mylis)

Even simpler, you could use str.upper instead of importing from string (thanks to @alecxe):

>>> map(str.upper, mylis)

In Python 2.x, map constructs a new list by applying a given function to every element in a list. filter constructs a new list by restricting to elements that evaluate to True with a given function.

In Python 3.x, map and filter construct iterators instead of lists, so if you are using Python 3.x and require a list the list comprehension approach would be better suited.

Solution 2 - Python

Or, alternatively, you can take a list comprehension approach:

>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]

Solution 3 - Python

Sometimes you need to apply a function to the members of a list in place. The following code worked for me:

>>> def func(a, i):
...     a[i] = a[i].lower()
>>> a = ['TEST', 'TEXT']
>>> list(map(lambda i:func(a, i), range(0, len(a))))
[None, None]
>>> print(a)
['test', 'text']

Please note, the output of map() is passed to the list constructor to ensure the list is converted in Python 3. The returned list filled with None values should be ignored, since our purpose was to convert list a in place


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshantanuoView Question on Stackoverflow
Solution 1 - PythonmdmlView Answer on Stackoverflow
Solution 2 - PythonalecxeView Answer on Stackoverflow
Solution 3 - PythonefimpView Answer on Stackoverflow