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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I think you mean to use map instead of filter:
>>> from string import upper >>> mylis=['this is test', 'another test'] >>> map(upper, mylis) ['THIS IS TEST', 'ANOTHER TEST']
Even simpler, you could use str.upper instead of importing from string (thanks to @alecxe):
>>> map(str.upper, mylis) ['THIS IS TEST', 'ANOTHER TEST']
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.
Method 2
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']
Method 3
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 methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0