Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Lambda Expressions in Python

0.00/5 (No votes)
21 May 2015 1  
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.)

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.
Colourised in 9ms

We could also write the code in the below way:

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)
Colourised in 6ms

But it is much simpler to code like below:

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)
Colourised in 5ms

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:

a = lambda x:x%2
print a(2)
Colourised in 0ms

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:

x = lambda x:x%2
Colourised in 0ms

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:
list=[1,2,3,4]
Colourised in 0ms

Now I will say:

print map(lambda x:x%2 == 0,[1,2,3,4])
Colourised in 0ms

The output will be:

[False, True, False, True]
Colourised in 0ms

Ok.

One more example:

print filter(lambda x:x%2 == 0,[1,2,3,4])
Colourised in 0ms

We get:

[2, 4]
Colourised in 0ms

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here