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.
Use the map() Function to Apply a Function to a List in Python. The map() function is used to apply a function to all elements of a specific iterable object like a list, tuple, and more. It returns a map type object which can be converted to a list afterward using the list() function.
lapply() function in R Programming Language is used to apply a function over a list of elements. lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With