List in python is a data structure that allows you to store multiple values in a single variable. It is mutable and can be added with other elements in the future using the append() method in python. Suppose you have a list and want to apply a function to each element of the list then How you can do so? In this entire post, you will know how to apply a function to each element of the list in python using different methods.
Methods to apply the function to each element of the list in python
Let’s explore all the methods that can help you to apply the function to each element in the list.
Method 1: Using the map() method
You can apply the function to each element of the list using the map() function. The map() function will accept your list and the function as arguments or parameters.
Suppose I have a function that squares each element of the list.
my_list = [1,2,3,4,5]
def square(x):
return x*x
Now pass your list and function to the map() function to square each element of the list.
result = map(square,my_list)
print(list(result))
Output

Method 2: Using for loop
The second method you can use is the for a loop. Here you will first create an empty list and add the squared elements to it after each iteration of the element.
my_list = [1,2,3,4,5]
def square(x):
return x*x
result_list = []
for e in my_list:
result_list.append(square(e))
print(result_list)
Output

Method 3: Pandas apply() function
You can apply a function to each element of the list in python using the panda’s module also. Here you will convert the list to dataframe and then apply the function on that using the apply() function.
import pandas as pd
my_list = [1,2,3,4,5]
df = pd.DataFrame(my_list)
def square(x):
return x*x
result = df[0].apply(square)
print(list(result))
Output

Method 4: Using applymap() method
There is another function provided by the pandas module and it is applymap() method. This function will accept only the square function as an argument.
import pandas as pd
my_list = [1,2,3,4,5]
df = pd.DataFrame(my_list)
def square(x):
return x*x
result = df.applymap(square)
print(list(result[0]))
Output

Conclusion
As you can see, there are many ways to apply a function to each element of a list in Python. You can use a for loop, map, pandas apply, or applymap method. Each method has its own advantages and disadvantages. It’s up to you to choose the right method for your particular situation.
Leave a Reply