Python

1. Lambda Function

Syntax of Lambda Function in python

# lambda arguments: expression
double = lambda x: x * 2

# Eg1: Output: 10
print(double(5))

# eg2:
my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

# Output: [4, 6, 8, 12]
print(new_list)

# eg3:
my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

# Output: [2, 10, 8, 12, 16, 22, 6, 24]
print(new_list)

Example use with filter(), Map()

Thefilter()function in Python takes in a function and a list as arguments.

The function is called with all the items in the list and a new list is returned which contains items for which the function evaluats toTrue.

Themap()function in Python takes in a function and a list.

The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item.

https://www.programiz.com/python-programming/anonymous-function

results matching ""

    No results matching ""