AIKISS
Published in

AIKISS

Python_Functions, Lambda, Map and Reduce

Examples on Functions, Lambda and Map/Reduce

Photo by Ian Keefe on Unsplash

Functions, lambdas, and map/reduce can allow you to process your data in advanced ways. We will introduce these techniques here and expand on them in the next module, which will discuss Pandas.

Function parameters can be named or unnamed in Python. Default values can also be used. Consider the following function.

A function is a way to capture code that is commonly executed. Consider the following function that can be used to trim white space from a string capitalize the first letter.

This function can now be called quite easily.

Python’s map is a very useful function that is provided in many different programming languages. The map function takes a list and applies a function to each member of the list and returns a second list that is the same size as the first.

Map

The map function is very similar to the Python comprehension that we previously explored. The following comprehension accomplishes the same task as the previous call to map.

The choice of using a map function or comprehension is up to the programmer. I tend to prefer map since it is so common in other programming languages.

Filter

While a map function always creates a new list of the same size as the original, the filter function creates a potentially smaller list.

Lambda

It might seem somewhat tedious to have to create an entire function just to check to see if a value is greater than 5. A lambda saves you this effort. A lambda is essentially an unnamed function.

Reduce

Finally, we will make use of reduce. Like filter and map the reduce function also works on a list. However, the result of the reduce is a single value. Consider if you wanted to sum the values of a list. The sum is implemented by a lambda.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sanjay.M

Sanjay.M

Certified Data Science Associate, Machine Learning and AI Practitioner Github:-https://github.com/Msanjayds, Linked in: https://www.linkedin.com/in/sanjaymds/