While I am a bit of a programming language pragmatist and generally choose what I feel is the best language for the job, the language I use for work and most of my personal projects, big and small is Python. Python is a solid programming language with a lot of great features but one of my favorite language features that Python has is Lambda’s.
Lambdas are basically 1 line functions that are not bound to a variable name(anonymous) which are created at runtime. The idea itself for lambda functions comes from functional languages like Lisp and while its certainly not the same lambdas are still very powerful constructs in python. Lets look at some examples to make this concept a bit clearer.
A normal function in python looks like this:
def fun(x):
print x+25
fun(35)
the equivalent lambda function would be:
fun = lambda x: x +25
fun(35)
Both examples above will return the same result. Some additional things to remember about lambda functions:
1. a lambda function can be executed without assigning to a variable.
2. lambdas do not include return statements as they are expressions which are expected to return a result.
3. lambdas can be used anywhere a function can be used.
4. lambdas can not be longer than 1 line.
Here is another basic but hopefully clearer use of for lambda functions:
class Book():
def __init__(self, author="", title=""):
self.author = author
self.title = title
booklist = [Book("Douglas Coupland", "Microserfs"), Book("Neil Gaiman", "American Gods"), Book("Frank Herbert", "Dune")]
#sort books by title using a lambda function
booklist.sort(lambda x,y: cmp(x.title, y.title) )
#sort books by author using a lambda function
booklist.sort(lambda x,y: cmp(x.author, y.author))
I think all of this about lambda functions is pretty self explanatory but if you have any questions leave them in the comments and I will answer them in this post or a follow up post. I also have not tested these basic examples, so if you try it out and see any issues, let me know and I will fix it up here.