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.
# 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 thesq()function to each element of the lista. - The result of
map()is converted into a list usinglist(), creating a new list of squared numbers.
Let's explore some other methods to apply function to each element of a list in Python
Table of Content
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.
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
xin the lista. - For each element, it calculates the square (
x * x) and adds it to the new listsq_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.
# 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 listaby 2.- loop iterates over each element of the list
[1, 2, 3, 4]and appends the doubled value to thedoubled_numberslist. - The final list
doubled_numberscontains[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:
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 * 3function triples each element in the list[1, 2, 3, 4].- Using
map()is applied to every element, andlist()converts the result into a list. - The final list contains
[3, 6, 9, 12]after each element is multiplied by 3.