Perform function on list Python

This post will discuss how to apply a function to each member of a list in Python.

1. Using map[] function

The standard solution is to use the map[] function, which applies a function to every item of iterable and yield the results. The following code converts a list of lowercase characters to a list of uppercase characters:

1
2
3
4
5
6
7
if __name__ == '__main__':
chars = ['a', 'b', 'c']
upper = list[map[str.upper, chars]]
print[upper]# ['A', 'B', 'C']

DownloadRun Code

2. Using List Comprehension

You can also use list comprehension to construct a new list, where each element results from some function applied to each member of the given list. Following is a simple example demonstrating usage of this function:

1
2
3
4
5
6
7
if __name__ == '__main__':
chars = ['a', 'b', 'c']
upper = [ch.upper[] for ch in chars]
print[upper]# ['A', 'B', 'C']

DownloadRun Code

3. Using lambda function

Another plausible way of mapping is to create small anonymous functions using the lambda function. This is often useful when the conversion function is not available. To illustrate, the following code increments all values in the list by one.

1
2
3
4
5
6
7
if __name__ == '__main__':
odd = [1, 3, 5, 7, 9]
even = list[map[lambda x: x + 1, odd]]
print[even]# [2, 4, 6, 8, 10]

DownloadRun Code

Thats all about applying a function to each member of a list in Python.

Video liên quan

Chủ Đề