In this video you will learn about map() and filter() function and how to use lambda with them.
map() function
The map() function takes two arguments. The first argument is a function/lambda and second argument is a collection(list, set, tuple, and string etc). The map() applies the given lambda or function on every element of its argument collection, and returns a new iterator (map) that can be converted into list etc.
It have following syntax:
map(function,collection)
Note: The map() returns a map object, which should be converted into appropriate collection type.
Consider the following example:
list1=[1,2,3,4,5,6,7,8,9,10]
result=list(map(lambda x:x*2,list1))
print(result)
In the above example, we are passing a lambda which doubles its parameters value, and map applies this lambda on every element of list1. We change the map object returned by the map() into lis object using list() constructor.
filter() function
\
The filter() takes two arguments, the first argument is a function/lambda, which returns a Bool value, and second argument is a collection. The function returns a new filter object which contains only those elements of argument collection, for which the argument function returns True.
The returned value is converted into appropriate collection.
The filter() function have following syntax:
filter(function,collection)
Consider the following example:
list1=[10,11,12,21,22,34,56,67]
list2 = list(filter(lambda x: (x%2 == 0) , list1))
print(list2)
In the above example the filter function have a lambda as argument which returns True when it gets an Even element. So it returns a filter object containing only even values, which is converted into list.
In the below example we are extracting vowels from a string.
text="Python is cool"
vowels =list( filter(lambda x: (x in ['a','e','i','o','u']) , text))
print(vowels)
#python_by_tarun_sir #tarun_sir #python #tarun_sir_python #python_video_53 #lambda_function_with_map()_in_python #python_tutorial #lambda_in_python lambda_function_with_filter()_in_python
In questa pagina del sito puoi guardare il video online map() and filter() function in python della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Tarun Sir 25 aprile 2020, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 149 volte e gli è piaciuto 8 spettatori. Buona visione!