Apply function to each element of a list

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


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.


Try using a list comprehension:

>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]
['THIS IS TEST', 'ANOTHER TEST']