Fix Python – Apply function to each element of a list

Question

Asked By – shantanuo

Suppose I have a list like:

mylis = ['this is test', 'another test']

How do I apply a function to each element in the list? For example, I want to be able to apply str.upper to get

['THIS IS TEST', 'ANOTHER TEST']

Now we will see solution for issue: Apply function to each element of a list


Answer

Using the built-in standard library map:

>>> mylis = ['this is test', 'another test']
>>> list(map(str.upper, mylis))
['THIS IS TEST', 'ANOTHER TEST']

In Python 2.x, map constructed the desired new list by applying a given function to every element in a list.

In Python 3.x, map constructs an iterator instead of a list, so the call to list is necessary. If you are using Python 3.x and require a list the list comprehension approach would be better suited.

This question is answered By – mdml

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0