- Home
- Course Detail
regularpython@gmail.com
You are now watching:
Python Lambda / of Python Lambda Function Map,Filter And Reduce Examples 2
def sum(x,y): return x + y result = sum(3,4) print(result) double = lambda x: x * 2 a = [1,2,3,4,5,6,7] print(double(a))
# Map Function my_list = [1, 2, 3, 4, 5] def square(x): return x>3 result = map(square,my_list) print(list(result)) # result = filter(square,my_list) print(list(result)) # print(list(map(lambda x:x>3, [1, 2, 3, 4, 5]))) print(list(filter(lambda x:x>3, [1, 2, 3, 4, 5]))) new_list = list(map(lambda x: x * 2 , my_list)) # Output: [2, 10, 8, 12, 16, 22, 6, 24] print(new_list)
# reduce function The reduce function, reduce(function, iterable) applies two arguments cumulatively to the items of iterable, from left to right from functools import reduce numbers = [1, 2, 3, 4, 5] result = reduce(lambda x,y: x+y, numbers) print(result)
# filter function filter(function,iterable) creates a new list from the elmeents for which the function my_list = [1, 2, 3, 4, 5, 6] def big(x): return x>3 new_list = list(filter(big, my_list)) # print(new_list) new_list = list(filter(lambda x: (x%2 == 0) , my_list)) print(new_list)
subjects = [['Antham', 'Telugu', 2], ['Love Ke Funday', 'Hindi', 2.5], ['Kanupapa', 'Telugu', 1.6], ['Vismayam', 'Malayalam', 2]] subjects.sort(key = lambda x: x[1]) print(subjects) # subjects.sort(key = lambda x: x[2], reverse = False) # print(subjects) subjects = sorted(subjects, key = lambda x: x[2]) print(subjects)