官术网_书友最值得收藏!

Lambda functions

In Python, an anonymous function is a function that is defined without a name and is called a lambda function, as it is defined using a keyword lambda. We use these functions whenever we require a function for a short period of time.

Lambda functions are used along with built-in functions, such as filter(), and map().

The filter() function returns a list of elements and has only one iterable as input. The following shows an example using filter():

numbers = [10, 25, 54, 86, 89, 11, 33, 22]
new_numbers = list(filter(lambda x: (x%2 == 0) , numbers))
print(new_numbers)

Output:
[10, 54, 86, 22]

In this example, the filter() function is taking a lambda function and a list as an argument.

The map() function returns a list of results after applying the specified function. Now, let's look at an example using map():

my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)

Output:
[2, 10, 8, 12, 16, 22, 6, 24]

Here, the map() function is taking a lambda function and a list.

主站蜘蛛池模板: 宜宾县| 山东省| 南阳市| 漳平市| 罗城| 尉氏县| 玛沁县| 大余县| 林芝县| 遂宁市| 白银市| 南华县| 英德市| 巴中市| 拜城县| 贵定县| 安阳县| 大邑县| 卫辉市| 乌兰察布市| 沐川县| 湖南省| 阳春市| 右玉县| 玛沁县| 蓝山县| 莆田市| 屯门区| 五华县| 奉化市| 嘉义县| 峨眉山市| 舞钢市| 高淳县| 丰原市| 佛山市| 左权县| 岳西县| 从化市| 改则县| 留坝县|