Apply a Function to a List in Python

Apply a Function to a List in Python

Manav Narula Mar-21, 2021 Feb-26, 2021 Python Python List
  1. Use the for Loop to Apply a Function to a List in Python
  2. Use the map() Function to Apply a Function to a List in Python
  3. Use the List Comprehension Method to Apply a Function to a List in Python

A function is a block of code that can be called to perform a specific operation in programming. There are many built-in functions and also user-defined functions.

A list is a collection of different elements in Python under a common name. It stores elements at specific positions.

In this tutorial, we will discuss how to apply a function to a list in Python.

Use the for Loop to Apply a Function to a List in Python

This is the most straightforward method. We simply iterate through the list using the for loop and apply the required function to each element individually. We store the result in a separate variable and then append this variable to a new list.

In the following code, we apply a user-defined function, which multiplies a number to 10.

def fn(a):
    return 10 * a

lst = [1, 2, 3, 4]
ans = []

for i in lst:
    x = fn(i)
    ans.append(x)
print(ans)

Output:

[10, 20, 30, 40]

Use the map() Function to Apply a Function to a List in Python

The map() function is used to apply a function to all elements of a specific iterable object like a list, tuple, and more. It returns a map type object which can be converted to a list afterward using the list() function.

For example,

def fn(a):
    return 10 * a

lst = [1, 2, 3, 4]

ans = list(map(fn, lst))
print(ans)

Output:

[10, 20, 30, 40]

Use the List Comprehension Method to Apply a Function to a List in Python

List Comprehension is a concise, elegant way to create lists in Python. In a single line of code, we will apply the function to all the list elements and store it in the new list using the list comprehension method.

The following code implements this.

def fn(a):
    return 10 * a

lst = [1, 2, 3, 4]

ans = [fn(i) for i in lst]

print(ans)

Output:

[10, 20, 30, 40]

We can also use all these methods mentioned in this tutorial with built-in functions.

Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python List

  • Convert a Dictionary to a List in Python
  • Remove All the Occurrences of an Element From a List in Python
  • Remove Duplicates From List in Python
  • Get the Average of a List in Python
  • What Is the Difference Between List Methods Append and Extend
  • Convert a List to String in Python