Posted March 29, 2010 by Spyros in Python Programming

How to Create And Use Lambda Anonymous Functions in Python


Lambda functions are an interesting and quite useful Python feature, that you have most certainly witnessed in other programming languages as well, probably as anonymous. A lambda function is really a way to create an “on the fly” function that can be used in Python expressions. Let’s take a look at a short example of a simple lambda function :

func = lambda x: x + 2
print func(4)

Upon execution, this prints the number 6 on your screen. Quite simply, we create a lambda function that gets a parameter and returns this integer parameter after adding 2 to it. Notice the syntax here. “lambda x: x + 2”. If this was a standard Python function, the code would be like :

def myfunc(x):
  return x + 2

Notice the differences ? As you see, a lambda function is a way to create a simple function quickly, without having to define it as usual. You may wonder why a lambda function can be important, but this is easily identified if you think of a function like map or filter in python.

Use a Lambda Function Along With The Filter Function

Filter is a very important Python function that gets a list as input and returns a new filtered list, according to our presets. To use filter, we provide it with a list and a function that filters that list. This is where a lambda function is most times used. Let’s take a look at this interesting example :

list = [1,2,3,4,5]

newList = filter(lambda x: x - 1, list)
print newList

After this is executed, it returns [2,3,4,5], but do you understand why ? First of all, we create a lambda function that gets an integer and returns the same integer subtracted by 1. Now, filter works like this. If the function returns true, the item is returned to the newList. Each element of the list is passed through the lambda function for evaluation. The first integer value of the list is 1. When subtracted by 1, it returns the integer 0. However, 0 means False as you know and the element is not passed to the newList. The second element 2 becomes 1, 3 becomes 2 and so forth and all these values, since they are not 0, are evaluated as true and passed to the newList.