Apply function to each element of a list
Solution 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.
Solution 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']
Solution 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