How to Use Lambda for Efficient Python Code | by Khuyen Tran | Towards Data Science

What this graph reminds you of? Amplification of amplitude in a wave? How can this be made? You take a closer look at the graph and realize something interesting. It looks like as x increases, the value on the y-axis first goes down to -1 then goes up to 1, goes down to -2 then goes up to 2, and so on. This gives you the idea that the graph can be made using a list like this
[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9]
If you use matplotlib with the list above as an argument, you should have the graph that is close to the graph above:
This looks easy. Once you understand how the graph could be created using a list, you could easily recreate the wave graph. But what if you want to create a much cooler graph that requires a much bigger list, like this?
You definitely don’t want to write the list above manually with 200 numbers on the list. So you have to figure out how to use Python to create the list with the number range from (n,m)
but with the 0 starts at the beginning, proceeded by -1, 1,-2,2,...n.
This list is not difficult to create if we realize that the list sorted by the absolute value of the elements |0|, |-1|, |1|, |-2|, |2|, .., n. So something with sorted and absolute value would work? Bingo! I will show you how to easily create this sort of function on one line of code with lambda.
Hey, I am glad you ask. lambda keyword in Python provides a shortcut for declaring small anonymous functions. It behaves just like regular functions. They can be used as an alternative for function objects. Let’s have a small example of how to replace function with lambdas:
def mult(x,y):  return x*ymult(2,6)
Outcome: 12
We can make the code above shorter with lambda
mult = lambda x, y: x*ymult(2,6)
But do we need to define the name of the multiplication anyway? After all, we just want to create a function that could multiply 2 numbers right? We can reduce the function above to even simpler code:
(lambda x, y: x*y)(2, 6)
That looks shorter. But why should you bother to learn about lambda , just to save a few lines of code anyway? Because lambda could help you create something more sophisticated easily. Like sorting a list of tuples based on their alphabets:
tuples = [(1, 'd'), (2, 'b'), (4, 'a'), (3, 'c')]sorted(tuples, key=lambda x: x[1])
Outcome:
[(4, 'a'), (2, 'b'), (3, 'c'), (1, 'd')]
This gives you a hint of how to create a graph above using lambda. Ready? Here it is:
import matplotlib.pyplot as pltnums = plt.plot(sorted(range(-100, 101), key=lambda x: x * x))plt.plot(nums)
Give us the graph:
Want to create a function that could take a number to the power of another number? We could use the combination of nested function and lambda :
def power(n):  return lambda x: x**npower_3 = power(3)list(map(power_3,[2,3,4,5]))
Outcome:
[8, 27, 64, 125]
Or use lambda to manipulate a pandas Dataframe
import pandas as pddf = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
#Create the 4th column that is the sum of the other 3 columnsdf['d'] = df.apply(lambda row: row['a']+row['b']+row['c'],axis=1)
Congratulation! Now you know how to use lambda as a shortcut for functions. I encourage you to use lambda when you want to create a nameless function for a short period of time. You could also use it as an argument to a higher-order function like above or used along with functions like filter() , map() , apply().
I hope this tutorial will give you some motivations and reasons to switch some of your Python code with lambda . A small change in your code could give you a big return in time and efficiency as you increasingly incorporate more sophisticated code for your data science projects.
Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: