confused with lambda~
Sean 'Shaleh' Perry
shalehperry at attbi.com
Tue Sep 24 11:15:15 EDT 2002
On Tuesday 24 September 2002 01:48, black wrote:
> that describe in reference documentation is too short, I couldnt even
> understand what it trying to say. any explanation please ?
>
lambda is way to define a function without giving it a name.
lambda x,y: x + y
defines a function which takes two parameters -- x and y -- and returns their
sum.
do_sum = lambda x,y: x + y
do_sum(2,3)
yields 5. As you can see we store the function as do_sum. So let's take this
a step further.
numbers = range(1,21) # numbers 1 - 20
sum = reduce(lambda x,y: x + y, numbers)
sum will be the sum of all numbers 1 - 20. This is equivalent to the
following code:
sum = 0
for n in numbers:
sum = sum + do_sum(sum, n)
The idea is lambda let's you write little one off functions when you need them
rather than have to define one somewhere and likely only use it once.
In a lambda on expressions are valid so no assignment or print calls can
happen. If you need that you must define a function.
Hope this helps.
More information about the Python-list
mailing list