[Tutor] [Python-Help] What is lambdas in Python??

bob gailer bgailer at gmail.com
Wed Dec 28 03:08:30 CET 2011


On 12/27/2011 8:36 PM, Hitesh Kumar wrote:
> I really don't get it. What is lambda? I keep seeing it and I couldn't 
> understand anything online about it.

lambda
    An anonymous inline function consisting of a single /expression/
    <#term-expression> which is evaluated when the function is called.
    The syntax to create a lambda function is lambda [arguments]: expression

It is a way to create a simple anonymous function.

func = lambda x, y : x + y

is the equivalent of

def func(x, y):
     return x = y

Handy when the function returns an expression (no compound statements) 
and does not need a name, e.g.
map(lambda x, y : x + y,  (1,2,3), (4,5,6))

OK now you wonder what is map so:

map(/function/, /iterable/, /.../)
    Apply /function/ to every item of /iterable/ and return a list of
    the results. If additional /iterable/ arguments are passed,
    /function/ must take that many arguments and is applied to the items
    from all iterables in parallel. If one iterable is shorter than
    another it is assumed to be extended with None items. If /function/
    is None, the identity function is assumed; if there are multiple
    arguments, map() <#map> returns a list consisting of tuples
    containing the corresponding items from all iterables (a kind of
    transpose operation). The /iterable/ arguments may be a sequence or
    any iterable object; the result is always a list.

 >>> print map(lambda x, y : x + y,  (1,2,3), (4,5,6))
[5, 7, 9]



-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111227/816b77fc/attachment-0001.html>


More information about the Tutor mailing list