Skip to content
Related Articles

Related Articles

Apply function to each element of a list – Python

View Discussion
Improve Article
Save Article
  • Last Updated : 26 Nov, 2020

In this article, we will learn how to apply a function to each element of a Python list. Let’s see what exactly is Applying a function to each element of a list means:

Suppose we have a list of integers and a function that doubles each integer in this list. On applying the function to the list, the function should double all the integers in the list. We achieve this functionality in the following ways:

  1. map() method.
  2. Using list comprehensions.
  3. lambda function

Using map() method

map() methods take two arguments: iterables and functions and returns a map object. We use list() to convert the map object to a list.

Program:

Python3




def double(integer):
    return integer*2
  
  
# driver code
integer_list = [1, 2, 3]
  
# Map method returns a map object
# so we cast it into list using list()
output_list = list(map(double, integer_list))
  
print(output_list)

Output:

[2, 4, 6]

Time Complexity: O(n)*(O complexity of function applied on list)

Using list comprehensions

We use a list comprehension to call a function on each element of the list and then double it for this case.

Program:

Python3




def double(integer):
    return integer*2
  
  
# driver code
integer_list = [1, 2, 3]
  
# Calling double method on each integer
# in list using list comprehension.
output_list = [double(i) for i in integer_list]
  
print(output_list)

Output:

[2, 4, 6]

Time Complexity: O(n)*(O complexity of function applied on list)

Using Lambda Function

A lambda function can also be employed to produce the above functionality. Lambda is capable of creating an anonymous function that can be made enough to fit the given requirement.

Program:

Python3




lst = [1, 2, 3]
  
ans = []
  
for x in lst:
    def res(x): return x*2
    ans.append(res(x))
  
print(ans)

Output:

[2, 4, 6]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!