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.
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.
map(str.upper, mylis)
would work too, would help to avoid astring
import.Note that
map
only constructs alist
on python2.x -- On python3.x it returns an iterator. Frequently that doesn't matter, but if you need a list as output, then it's probably better to use a list comprehension as in the other answer.Is approach the same for side effecting functions?
In Python 3.x, you can do
list(map(str.upper, mylis))
, if you want list.