DEV Community

Cover image for Python's Lambda, map, and filter
EzeanaMichael
EzeanaMichael

Posted on

Python's Lambda, map, and filter

Lambda

Perhaps you want to create a function that takes a function and an argument.
Something that looks like this
Code:
Image description
Output:
Image description
Here's it is written with the lambda function
Code:
Image description
Output:
Image description
Lambda is an in-built python function that can also be called an anonymous function that can be written in a single line for a particular function, though not as powerful as using "def" to create a function.
It is written in a format
(Lambda x: 2*x )(15)
Where it takes an argument x and multiplies it by 2 the second parentheses is the argument it takes in
Therefore printing this will result in 30
Code:
Image description
Output:
Image description
It can also be written in the format
Code:
Image description
Output:
Image description

Map and filter

These are inbuilt functions in python,
The map is used to pass a function over an iterable I.e a list
Code:
Image description
Output:

Image description
It takes in two arguments, the first is a function and the second is iterable.
The map function has to be explicitly converted into a list for the value to be seen.
Filter as the name implies is used to filter or remove items on the list based on certain conditions that are specified.
It takes in two arguments the first is the specified condition and the list
Consider the code
Code:
Image description
Output:
Image description
This is used when you need only certain elements in a list that specifies a condition.
Hope you enjoyed reading this
Like, share, and comment.

Top comments (0)