Related Articles

Related Articles

Apply function to each element of a list – Python
  • 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



filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

[2, 4, 6]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :