Open In App

Apply function to each element of a list – Python

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Applying a function to a list means performing a specific operation or transformation on each element of the list. For instance, we might want to multiply each element of a list by a constant or perform any custom operation using a function. In this article, we will explore various ways to Apply function to each element of a list.

Using map()

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

Python
# Function to square a number
def sq(x):
    return x * x

a = [1, 2, 3, 4]

# Applying the square function to each element
a= list(map(sq, a))
print(a)

Output
[1, 4, 9, 16]

Explanation:

  • The map() function applies the sq() function to each element of the list a.
  • The result of map() is converted into a list using list(), creating a new list of squared numbers.

Let’s explore some other methods to apply function to each element of a list in Python

Using list Comprehension

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

Python
a = [1, 2, 3, 4]

# Applying the square function using list comprehension
b = [x * x for x in a]
print(b)

Output
[1, 4, 9, 16]

Explanation:

  • This list comprehension loops through each element x in the list a.
  • For each element, it calculates the square (x * x) and adds it to the new list sq_num.

Using for Loop

A traditional for loop can also be used to apply a function to each element of a list. Here The loop iterates will through the list, applies the double function to each element and appends the result to a new list.

Python
# Function to double a number
def double(x):
    return x * 2

a = [1, 2, 3, 4]

# Using a for loop to double the elements
b = []
for num in a:
    b.append(double(num))

print(b)

Output
[2, 4, 6, 8]

Explanation:

  • double() function multiplies each element in the list a by 2.
  • loop iterates over each element of the list [1, 2, 3, 4] and appends the doubled value to the doubled_numbers list.
  • The final list doubled_numbers contains [2, 4, 6, 8], which is printed.

Using lambda with map()

Instead of defining a separate function we can use a lambda function directly with map(). This eliminates the need for a separately defined function.

Example:

Python
a = [1, 2, 3, 4]

# Using lambda to triple each number
tripled_nums = list(map(lambda x: x * 3, a))
print(tripled_nums)

Output
[3, 6, 9, 12]


Explanation:

  • x * 3 function triples each element in the list [1, 2, 3, 4].
  • Using map() is applied to every element, and list() converts the result into a list.
  • The final list contains [3, 6, 9, 12] after each element is multiplied by 3.


Next Article
Article Tags :
Practice Tags :

Similar Reads