question about what lamda does

grebekel at gmail.com grebekel at gmail.com
Tue Jul 18 11:38:41 EDT 2006


The two primary differences between using def and using lambda is that
lambda is limited to a single expression and def cannot be used within
another function.

Basically, use lambda when you need to define a small function within
another function. I've also used it to create 'shortcut' functions as:

bar = lambda a, b: object1.object2.function1( a ).function2( b )
foo = bar( somevalue1, somevalue2 )

It can save you a lot of typing if used wisely, and makes your code
smaller and neater too :)

On a real world example:

import random
roll_die = lambda sides=6: random.choice( range(1,sides+1) )
# roll dies with 4, 6, and 20 sides
print roll_die(4), roll_die(), roll_die(20)


Have fun with your lambdas.

greb

nephish at xit.net wrote:
> Hey there,
> i have been learning python for the past few months, but i can seem to
> get what exactly a lamda is for. What would i use a lamda for that i
> could not or would not use a def for ? Is there a notable difference ?
> I only ask because i see it in code samples on the internet and in
> books.
> 
> thanks for any clarity
> 
> sk




More information about the Python-list mailing list