Click here to Skip to main content
15,886,689 members
Articles / Programming Languages / Python
Tip/Trick

Lambda Expressions in Python

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
21 May 2015CPOL4 min read 10.9K   5  
This is a short tip about lamdba expressions in Python.

Lambda Functions

  • Lambda, you can say, is a tool for building a function (or you can also say function objects).
  • These are basically anonymous functions created at runtime which are not bound to the name of the functions.
  • They return the definition of the function on the fly.
  • Lambda functions don't contain a return statement, they always return an expression.
  • You can always put a lambda definition anywhere a function is expected.

Why Use Lambda?

We can go along without using it, but:

  1. It makes your code cleaner and easier.
  2. When you are just going to need a function once.
  • Functions you can say are used for:
    1. Modularity
    2. Code Reuse
  • If your application contains duplicate chunks of code, as that code is being reused, why not wrap it up in a function and call it wherever necessary.
  • But suppose we have a function which is to be used only once and called from only one place, then we can use lambda functions.
  • So you don't need to give it a name and you can define the functionality there itself.

Why Use a Function If We Need It Only Once???

  • The answer is in the question itself. Hence, we eliminate the use of a function and use Lambda.
  • Anything which could be short and satisfies the need to eliminate the use of a function, hence we use a lambda expression.

Why Create a Short Anonymous Function???

Consider this snippet of code that uses lambda to define the behavior of buttons in a Tkinter GUI interface. (This example is from Mike’s tutorial.)

C++
frame = tk.Frame(parent)
	frame.pack()
	btn22 = tk.Button(frame, 
    text="22", command=lambda: self.printNum(22))///function object being assigned to command parameter.
	btn22.pack(side=tk.LEFT)
	btn44 = tk.Button(frame, 
    text="44", command=lambda: self.printNum(44))///function object being assigned to command parameter.
	btn44.pack(side=tk.LEFT)
	frame = tk.Frame(parent)
	frame.pack()
 	btn22 = tk.Button(frame, 
    text="22", command=lambda: self.printNum(22))///function object being assigned to command parameter.
	btn22.pack(side=tk.LEFT)
 	btn44 = tk.Button(frame, 
    text="44", command=lambda: self.printNum(44))///function object being assigned to command parameter.

We could also write the code in the below way:

C++
def __init__(self, parent):
		"""Constructor"""
		frame = tk.Frame(parent)
		frame.pack()
 
		btn22 = tk.Button(frame, 
			text="22", command=self.buttonCmd22)
		btn22.pack(side=tk.LEFT)
 
		btn44 = tk.Button(frame, 
        text="44", command=self.buttonCmd44)
		btn44.pack(side=tk.LEFT)
 
	def buttonCmd22(self):
		self.printNum(22)
 
	def buttonCmd44(self):
		self.printNum(44)

But it is much simpler to code like below:

C++
def __init__(self, parent):
  	  """Constructor"""
      frame = tk.Frame(parent)
      frame.pack()
 	  btn22 = tk.Button(frame,text="22", command=lambda: self.printNum(22))
      btn22.pack(side=tk.LEFT)
      btn44 = tk.Button(frame, 
      text="44", command=lambda: self.printNum(44))
      btn44.pack(side=tk.LEFT)

As you can see that it becomes much easier to code and we will just use the function once (in the place where it needs to be.)

Now, let us look at some simpler examples:

C++
a = lambda x:x%2
print a(2)

This would give the result : 0

What am I trying to achieve here?

  • I want a function which will simply return the modulus of a number, I don't want to define it, because I would use it just once on the fly.
  • I would not reuse it more than once.
  • So what we observe here is that the lambda returns an expression which is assigned to 'a' and a can be used as a function. As you can see above.

Now what if I say:

C++
x = lambda x:x%2

This will also print 2 if I say x(2).

  • Don't get confused between the variable to which the lambda is assigned. It is not necessary to have the same variable name and the variable used inside the lambda function.
  • Both are different.
  • One is the variable to which I am assigning the lambda expression and the one used in the expression is the argument which we pass in the function.

The above explanation can be interpreted like below:

Let us move ahead to some more examples on lambda functions:

For example:

  • I have a list of numbers out of which I want to check the number which is divisible by '2'.
  • Okay, so I will define a list first:
C++
list=[1,2,3,4]

Now I will say:

C++
print map(lambda x:x%2 == 0,[1,2,3,4])

The output will be:

[False, True, False, True]

Ok.

One more example:

C++
print filter(lambda x:x%2 == 0,[1,2,3,4])

We get:

[2, 4]

After all of this discussion, there is one more question unanswered: "What is a lambda expression?" OR "What is the difference between an expression and a function?"

The answer is:

  • An expression evaluates to a value while a function does not.
  • If you see at the top, I have said: Lambda is a tool to create an anonymous function, instead of that I can easily say that lambda is a tool to create an anonymous procedure.

I hope basics of Lambda have been covered.

The session should be interactive, so I request you to try out a simple exercise.

Exercise

  • You can try out a program which would print the lengths of every string in a list?
  • Try out an assignment statement in Lambda. What happens? What is the reason for the outcome?
  • Pass a function call in a lambda expression, pass arguments in it and see what happens?
  • What are the uses of Map and Filter functions used in above examples?

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer EinfoChips.Ltd
India India
Born in India, have almost traveled around the country at an interval of every 2-3 years.
Now settled in a place where i am currently designated as a Senior Engineer :laugh.

My work experience lies in :
-> OS: VxWorks, WinCe, Windows
-> Languages : C,C#,Python
-> Application Development, Framework designing, Automation

_______________________________________________________________________________________
The real trouble with reality is that there's no background music.

Comments and Discussions

 
-- There are no messages in this forum --