Skip to content

Lambda, map() and filter()

surendrabisht edited this page Jul 14, 2020 · 2 revisions

Lambda

A lambda function is a small anonymous function.
Syntax: <lambda arguments> : <expression>
Ex:

reverse = lambda string : string[::-1]
print(reverse("Lambda"))

Map()

The map() function executes a specified function for each item in a iterable. The item is sent to the function as a parameter.

syntax: map(function,collection)

nos = [9,11,15]
doubleOfnos = map(lambda no: no*2, nos)
for x in doubleOfnos:
  print(x)

filter()

The filter() method constructs an iterator from elements of an iterable for which a function returns true.
syntax: filter(function,collection)

ages = [5, 12, 17, 18, 24, 32]
adults = filter(lambda age: age>18, ages)

for x in adults:
  print(x)

Clone this wiki locally