Saturday, December 28, 2024
Google search engine
HomeLanguagesApply function to each element of a list – Python

Apply function to each element of a list – Python

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)

RELATED ARTICLES

Most Popular

Recent Comments