[BangPypers] diffrerence between lambda function and ordinary one

Pradeep Gowda pradeep at btbytes.com
Fri Aug 6 16:36:16 CEST 2010


On Fri, Aug 6, 2010 at 10:20 AM, Rahul R <rahul8590 at gmail.com> wrote:
> i was writing some basic code . for understanding lambda functions , but
> couldnt understand the difference between a lambda function and an ordinary
> function.
>
> for example
>
>>>>def f (x): return x**2
> ...
>>>> print f(8)
>>>> 64
>>>> g = lambda x: x**2
>>>>
>>>> print g(8)
>>>> 64
>
> wats a need for using lambda functions ..?

You mean "what's the need for using lambda functions?"

Lambda functions are anonymous functions, ie., functions without a name.
Along with map, reduce, filter, lambda functions provide functional
programming[1]
constructs to python.

You can write code like this:

from operator import add
print reduce(add, filter(lambda x: x%2==0, xrange(10)))

to print the sum of even numbers less than 10
instead of:
tot = 0
for i in xrange(10):
....if i%2 == 0:
........tot += i
print tot

...

Anyway,
One does not "need" to use lambda function. Almost in all the places where
you use lambda functions, you can replace it with a named function with
added benefit of clarity.

Python lambdas are limited to a single statement, which makes them particularly
hobbled.

Guido is not very fond of FP constructs, in fact he wanted to remove
them from python 3.
After much discussion, lambda survived in Py3.


[1] http://en.wikipedia.org/wiki/Functional_programming


More information about the BangPypers mailing list