Return to the Lecture Notes Index

15-112 Lecture 26 (June 26, 2014)

Lambdas

There's one common detail of Python we haven't crossed in our travels. It isn't necessary. It has funny syntax. But, Python programmers love it. And, using it at every opportunity is characteristic of those steeped in Python culture -- and avoiding it is characteristic of being new to the language or just dabbling from time-to-time. Even better, it sounds complicated, because it has a cool Greek-sounding name. But, theory people love it -- for its simplicity and elegance.

Python provides a way of defining what are, effectively, short, anonymous functions called lambdas. They are short in the sense that they, literally, map from a variable to a value without any other parameters. They are anyonymous in the sense that they don't have names.

But, let's not read too much into the anonymous part. Although they technically don't have names -- we can assign them to variables, which serve as names. Check out the example below:


square = lambda x: x**2
print square (4)
         

Even more interesting, we can use functions to parameterize lambdas. Notice the example below, where the lambda is defined using an additional variable provided via a function:


def power(n): return lambda x: x**n
power3 = power(3)

print power3(2)