Custom Search

Friday, April 2, 2010

What is Lambda in Python

What is Lambda in Python

Python's lambda allows you to declare a one-line nameless minifunction on the fly.
The format is:
lambda parameter(s): expression using the parameter(s)
It returns the result of the expression. The expression has to be a one-liner
(no newlines)! Here is a little example ...

import string
wordList = ['Python', 'is', 'really', 'great', 'stuff']
wordList.sort()
print "After standard sort (ASCII upper case is before lower case):"
print wordList

wordList.sort(lambda x, y: cmp(string.lower(x), string.lower(y)))
print "After case insensitve sort with lambda and lower:"
print wordList

No comments:

Post a Comment