Python - How To Apply a Function to a List in Python

ID : 300

viewed : 62

Tags : PythonPython List

vote vote

99

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.

  • Related HOW TO?