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 :
['THIS IS TEST', 'ANOTHER TEST']
I know upper
is built-in. This is just an example.
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
Or, alternatively, you can take a list comprehension
approach:
>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]
['THIS IS TEST', 'ANOTHER TEST']
Source: Stackoverflow.com