Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply function to each element of a list

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.

like image 427
shantanuo Avatar asked Aug 01 '14 14:08

shantanuo


People also ask

How do you apply a function to each element of a list?

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.

How do I apply a function to a list in R?

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.


1 Answers

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.

like image 195
mdml Avatar answered Sep 21 '22 20:09

mdml