How to apply a function to list in Python?

Ways to apply a function to list in Python

The most efficient way to apply a function to list in Python is by using the map() function. This function applies a given function to all elements of a list.

To apply a function to list in Python:

  1. 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 list() 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 loop to iterate over the list and apply the function to every element individually. To do this efficiently, we can use the list comprehension technique. This method creates a new list in a single line of code.

To apply a function to list in Python:

  1. Use the for loop to iterate over the list.

  2. 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 loop and apply the function to every element individually.

Explore more from this category at Python Lists. Alternatively, search and view other topics at All Tutorials.