Python lambda sample usage

This will be a very brief post on the sample usage of python’s lambda function.  The following code is an identity function that will return the argument passed in. Nothing too special but it will help demonstrate the syntax. In this case I’m defining the symbol id to the lambda function.

id = lambda x: x

The following snippet contains some sample use cases of the id symbol.

print(id(2)) # prints integer 2
print(id("Hello World")) # prints string "Hello World"

Here is a code snippet that is a bit more useful. The following code is a bit hack that finds the least significant bit(LSB) in a number, meaning the lowest bit that is used to generate the given number.

lsb = lambda x: x & (-x)

As an example, passing in 8 (1000) will return 8 as the LSB. When a more complex number like 6 (0110) is passed in the LSB will be 2.

print( lsb(8) ) # prints 8
print( lsb(6) ) # prints 2

You can also nest lambda’s together in Python. The next code snippet finds the sum of two numbers.

sum = lambda x: lambda y: x+y

So, how do you define the value of y when lambda expressions only take in a single argument? Well when you define the values of x and y in the expression, you use two sets of parenthesis. Each parenthesis will pass in the argument into the targeted lambda function.

print(sum(2)(2)) # prints 4
print(sum(2)(4)) # prints 6
print(sum(2)("Hello World")) # raises type error

My last code snippet defines a symbol min as a lambda expression. Min is contains a nested lambda expression that uses a bit hack to compare two integer values.

min = lambda x: lambda y: y ^((x^y) & -(x<y))

Here is a sample use case min.

print(min(2)(4)) # prints 2
print(min(4)(2)) # prints 2

Additional Resources:
http://en.wikipedia.org/wiki/Lambda_calculus

Lecture 2A – Higher Order Procedures: Structure and Interpretation of Computer Programs
[youtube:http://www.youtube.com/watch?feature=player_embedded&v=erHp3r6PbJk%5D

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s