Apply function to each element of a list

Question:

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, how do I apply str.upper to get:

['THIS IS TEST', 'ANOTHER TEST']
Asked By: shantanuo

||

Answers:

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.

Answered By: mdml

Try using a list comprehension:

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

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

Answered By: efimp

String methods in Python are optimized, so you’ll find that the loop implementations mentioned in the other answers here (1, 2) to be faster than vectorized methods in other libraries such as pandas and numpy that perform the same task.

In general, you can apply a function to every element in a list using a list comprehension or map() as mentioned in other answers here. For example, given an arbitrary function func, you can either do:

new_list = [func(x) for x in mylis]
# or 
new_list = list(map(func, mylis))

If you want to modify a list in-place, you can replace every element by a slice assignment.

# note that you don't need to cast `map` to a list for this assignment
# this is probably the fastest way to apply a function to a list 
mylis[:] = map(str.upper, mylis)
# or
mylis[:] = [x.upper() for x in mylis]

or with an explicit loop:

for i in range(len(mylis)):
    mylis[i] = mylis[i].upper()

You can also check out the built-in itertools and operator libraries for built-in methods to construct a function to apply to each element. For example, if you want to multiply each element in a list by 2, you can use itertools.repeat and operator.mul:

from itertools import repeat, starmap
from operator import mul

newlis1 = list(map(mul, mylis, repeat(2)))
# or with starmap
newlis2 = list(starmap(mul, zip(mylis, repeat(2))))

# but at this point, list comprehension is simpler imo
newlis3 = [x*2 for x in mylis]
Answered By: cottontail