The most efficient way to apply a function to list in Python is by using the function. This function applies a given function to all elements of a list.
To apply a function to list in Python:
-
Use the
map()
function to apply a function to list in Python.
# Apply a function to list in Python def f(a): return a*a # Create a list lst = [12, 23, 31] # Use the map() function to apply a function to list in Python lst_fun = list(map(f,lst)) print(lst_fun) # Output: [144, 529, 961]
In the above code sample, we use the map()
function to apply a function to list in Python. The function converts the returned map
-type object to a list.
In Python 2, the
map()
function returns a list by default.
We can also use the for
To apply a function to list in Python:
-
Use the
for
loop to iterate over the list. -
Apply the function to every element individually.
# Apply a function to list in Python def f(a): return a*a # Create a list lst = [12, 23, 31] lst_fun = [f(i) for i in lst] print(lst_fun) # Output: [144, 529, 961]
To conclude.
This particular article demonstrates different ways to apply a function to list in Python. The most efficient way is to use the map()
function. In the following method, we also demonstrate how to use the for
Explore more from this category at Python Lists. Alternatively, search and view other topics at All Tutorials.