How to Apply Function to a List in Python

In this tutorial, we will discuss how to apply Function to a list in Python. There are many ways of applying a function to every element in the list. We will discuss four different methods here.

  • Applying Function to a list using for loop in python.
  • Applying Function to all members or elements of a list using Map() Function.
  • Use List Comprehension to apply function to a list.
  • Apply Lambda Function to a list in Python.

Applying function to a list Using For loop in python

Python has some built-in functions and the Map function is one of them. Let’s consider you have a list of some numbers and you want to perform multiplication of 10 to each element in the list. If you don’t know about Map() Function, this is the simplest way to go through it.

  • We will create a new list.
  • Run a for loop.
  • For each iteration, every element is multiplied by 10.
  • It will save it to new list.
  • We can get our desired output using this method.
list = [1,2,3,4,5,6,7,8]

newlist  = []

for num in list:

   newlist.append(num*10)

print(newlist)

Output:

[10, 20, 30, 40, 50, 60, 70 ,80]

Here, we have got our desired output. All of the numbers are in the power of 10.

Applying Function to all members or elements of a list using Map() Function

Map Function has a lot of advantages. Let’s say, you need to implement the same problem using Map() Method. It takes two arguments: functions and iterables and returns a map object. We will use list() to convert the map object to a list.

list1 = [1,2,3,4,5,6,7,8]

newlist = list (map(lambda number: number * 10, list1))

print(newlist)

Ouput:

We have got our desired output and every number is multiplied by 10.

[10, 20, 30, 40, 50, 60, 70 ,80]

Use a list comprehension to apply function to a list

List comprehension is the method that would iterate through the list and multiply each number in the list with 10, also adding the multiplied items in another list i.e., “newlist”.

def double(num):
    return num*10
  

ls = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  
newlist = [double(i) for i in ls]
  
print(newlist)

Output:

[10, 20, 30, 40, 50, 60, 70 ,80, 90]

apply lambda function to list in python

Lambda Function is capable of creating an anonymous function that can be made enough to fit the requirement.

ls = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  
newlist = []
  
for num in ls:
    def res(num): return num*10
    newlist.append(res(num))
  
print(newlist)

Output:

[10, 20, 30, 40, 50, 60, 70 ,80, 90]

For any queries related to applying a function to a list in Python, Python Programming, Contact Us.

Leave a Comment

Your email address will not be published. Required fields are marked *