To apply a function to a list in Python, the easiest way is to use list comprehension to apply a function to each element in a list.
def add_one(x):
return x + 1
example_list = [0, 1, 2, 3, 4, 5]
print([add_one(i) for i in example_list])
#Output:
[1, 2, 3, 4, 5, 6]
You can also use the map() function.
def add_one(x):
return x + 1
example_list = [0, 1, 2, 3, 4, 5]
print(list(map(add_one, example_list)))
#Output:
[1, 2, 3, 4, 5, 6]
When working with collections of data in Python, the ability to easily manipulate and change these collections can be very valuable.
One example of this might be if you have a function you want to apply to each of the elements of a list.
We can easily apply a function to all elements in a list.
The easiest way is with list comprehension.
Below is an example of how to use list comprehension to apply a function to a list.
def add_one(x):
return x + 1
example_list = [0, 1, 2, 3, 4, 5]
print([add_one(i) for i in example_list])
#Output:
[1, 2, 3, 4, 5, 6]
Using map() to Apply a Function to a List in Python
The Python map() function is very useful and allows us to apply a function to a list.
To use map(), we just need to pass a function and a list to map, and then convert the returned value back to a list.
Below is a simple example of using map() to apply a function to a list of integers in Python.
def add_one(x):
return x + 1
example_list = [0, 1, 2, 3, 4, 5]
print(list(map(add_one, example_list)))
#Output:
[1, 2, 3, 4, 5, 6]
Using a Lambda Expression inside map() to Apply a Function to a List in Python
The map() function can take both regular functions and lambda functions. Let’s do the same operation as above but instead let’s use a lambda expression in map().
Below shows you how you can use a lambda function in map() to apply a function to a list in your Python code.
example_list = [0, 1, 2, 3, 4, 5]
print(list(map(lambda x: x+1, example_list)))
#Output:
[1, 2, 3, 4, 5, 6]
Hopefully this article has been useful for you to learn how to apply functions to lists in your Python code.